I have some json, example below:
[
{
"category": {
"name": "Technology",
"key": "012"
}
},
{
"category": {
"name": "Kitchen",
"key": "016"
}
},
{
"category": {
"name": "Technology",
"key": "012"
}
}
]
I want to count the occurrences from the data and map them to create a list in a react component. I want to display, the name, key and occurrences they appear in the list. And I want to display only 1 instance of the item with its occurrences in the list. I want to use Lodash to achieve this.
// 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]} />
)}
The desired outcome I'm looking for, is to list only one instance of each category in the list, with the name, count and key. It seems I can only count the occurrences of .name or .key which in turn means I can't include the other in my map. How can I achieve this using Lodash?