【发布时间】:2021-11-14 11:49:17
【问题描述】:
我有一些 json,示例如下:
[
{
"category": {
"name": "Technology",
"key": "012"
}
},
{
"category": {
"name": "Kitchen",
"key": "016"
}
},
{
"category": {
"name": "Technology",
"key": "012"
}
}
]
我想从数据中计算出现次数并将它们映射以在反应组件中创建一个列表。我想显示它们出现在列表中的名称、键和出现次数。而且我只想显示该项目的 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 实现这一目标?
【问题讨论】:
标签: javascript reactjs lodash