对嵌套对象使用 Lodash countBy

Using Lodash countBy for nested objects

我有一些 json,示例如下:

[
 {
  "category": {
   "name": "Technology",
   "key": "012"
  }
 },
 {
  "category": {
   "name": "Kitchen",
   "key": "016"
  }
 },
 {
  "category": {
   "name": "Technology",
   "key": "012"
  }
 }
]

我想计算数据的出现次数并将它们映射以在 React 组件中创建一个列表。我想显示它们出现在列表中的名称、键和出现次数。我只想显示该项目的 1 个实例及其在列表中的出现。我想用 Lodash 来实现这个。

// Example 1 - Lists each category with the correct values. eg. Technology(012,2), Kitchen(016,1), Technology(012,2).
const categories = items.map( item => item.category )
const countCategories = countBy(categories)

// React Component
{ Object.keys(categories).map(category =>
 <CustomComponent category={category.name} key={category.key} count={countCategories[category.name]} />
// Example 2 - Lists only one instance of each unique category by name with the count but not the key. eg. Technology(,2), Kitchen(,1)
const categories = items.map( item => item.category.name )
const countCategories = countBy(categories)

// React Component
{ Object.keys(countCategories).map(category =>
 <CustomComponent category={category} key={'NA'} count={countCategories[category]} />
)}

我正在寻找的期望结果是在列表中仅列出每个类别的一个实例,包括名称、计数和键。看来我只能计算 .name.key 的出现次数,这反过来意味着我不能将另一个包含在我的地图中。如何使用 Lodash 实现此目的?

使用 Array#reduce, iterate over the list while updating a Map,其中键是类别名称,值是具有更新计数的类别。

结果将是地图的最终值,这些值是按 name 分组的类别,每个类别的最终值是 count:

const arr = [
 { "category": { "name": "Technology", "key": "012" } },
 { "category": { "name": "Kitchen", "key": "016" } },
 { "category": { "name": "Technology", "key": "012" } }
];

const res = [...
  arr.reduce((categoryMap, { category }) => {
    if(categoryMap.has(category.name)) {
      categoryMap.get(category.name).count++;
    } else {
      categoryMap.set(category.name, {...category, count: 1});
    }
    return categoryMap;
  }, new Map)
  .values()
];

console.log(res);

使用 lodash,您可以使用 _.groupBy()category.name 对项目进行批处理,然后映射组,并创建一个类别数组,计数为:

const arr = [
 { "category": { "name": "Technology", "key": "012" } },
 { "category": { "name": "Kitchen", "key": "016" } },
 { "category": { "name": "Technology", "key": "012" } }
];

const result = _.map(
  _.groupBy(arr, 'category.name'),
 items => ({
  ...items[0].category,
  count: items.length
 })
)

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>