【发布时间】:2022-01-06 04:00:35
【问题描述】:
我有一个对象数组,我想将它们转换为使用图表中的数据。有人推荐使用 lodash,但我不想使用任何库。所以这里是数组的例子:
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',
},
},
},
]
我想要这样的输出,这是图表所需的格式。
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},
]
这是我来的最远的,但只是总数。
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,
}),
)
【问题讨论】:
标签: javascript arrays json object