I have an array of objects, and I want to convert them to consume the data in a chart. Someone recommends using lodash, but I don't want to use any libraries. So here is the example of the array:
const items = [
{
priceChangeType: 'CL',
hierarchy: {
department: {
description: 'TEXTILES',
},
},
},
{
priceChangeType: 'PM',
hierarchy: {
department: {
description: 'CLOTHES',
},
},
},
{
priceChangeType: 'CL',
hierarchy: {
department: {
description: 'TEXTILES',
},
},
},
{
priceChangeType: 'CL',
hierarchy: {
department: {
description: 'CLOTHES',
},
},
},
{
priceChangeType: 'PM',
hierarchy: {
department: {
description: 'BATH',
},
},
},
{
priceChangeType: 'PM',
hierarchy: {
department: {
description: 'TOOLS',
},
},
},
{
priceChangeType: 'CL',
hierarchy: {
department: {
description: 'TOOLS',
},
},
},
{
priceChangeType: 'CL',
hierarchy: {
department: {
description: 'TOOLS',
},
},
},
]
And I want an output like this, and this is the format needed for the chart.
const data = [
{name: 'TOOLS', PM: 1, CL: 2},
{name: 'CLOTHES', PM: 1, CL: 1},
{name: 'TEXTILES', PM: 0, CL: 2},
{name: 'BATH', PM: 1, CL: 0},
]
This is the furthest I've come, but only the total counts.
const totalPriceChangesType = Object.entries(items.reduce((r, v, i, a, k = v.priceChangeType) => ((r[k] || (r[k] = [])).push(v), r), {})).map(
([key, value]) => ({
[key] : value.length,
}),
)