我有一个对象数组,如下所示。这有点复杂,但我会尽力以简单的方式进行解释。正如您所看到的,每个名称为
Engineering
、Environment
和 others
的对象都有其 radars
对象。这个 radars
对象中有 all
对象,并且它应该有 p1
、p2
、p3+
和 total
。如果其中任何一个缺失,则意味着其计数为 0。对于 Environment
,p1
和 p2
缺失。这意味着它的计数为 0 等等。
let input = [
{
"name": "Engineering",
"radars": {
"all": {
"p1": { "count": 4 },
"p2": { "count": 1 },
"p3plus": { "count": 2 },
"total": { "count": 7 }
},
}
},
{
"name": "Environment",
"radars": {
"all": {
"p3plus": { "count": 1 },
"total": { "count": 1 },
}
}
},
{
"name": "others",
"radars": {
"all": {},
}
}
]
这是我需要得到的输出。我需要创建键为
P1
、P2
、P3+
和 Total
的对象数组。基本上,我想迭代输入对象并获取其 radar
对象。无论 p1
、p2
、p3+
和 total
的计数是多少,我都需要将它们一一传递给结果。例如在第一个带有 Engineering
的对象中,我有 p1
、p2
、p3+
和 total
为 4
、1
、2
、7
。因此,这些值将传递给输出中的每个键。类似地,传递下一组值。
const output = [
{ "P1": [ 4, 0, 0 ] },
{ "P2": [ 1, 0, 0 ] },
{ "P3+": [ 2, 1, 0] },
{ "Total": [ 7, 1, 0 ] }
]
有人可以让我知道如何实现这一目标吗?这比对象数组的正常循环稍微复杂一些,我无法找到任何特定于这种复杂性的东西。
您可以使用reduce而不是单个对象的数组来创建
{ p1: [4, 0, 0], p2: [1, 0, 0], p3plus: [2, 1, 0], total: [7, 1, 0] }
格式的对象。可以对keys数组进行循环,也可以得到对应的值
let input = [ { "name": "Engineering", "radars": { "all": { "p1": { "count": 4 }, "p2": { "count": 1 }, "p3plus": { "count": 2 }, "total": { "count": 7 } }, } }, { "name": "Environment", "radars": { "all": { "p3plus": { "count": 1 }, "total": { "count": 1 }, } } }, { "name": "others", "radars": { "all": {}, } } ]
const res = input.reduce((acc,curr,idx) => {
const radars = Object.keys(curr.radars.all)
radars.forEach(r => {
acc[r] = acc[r] || Array(input.length).fill(0)
acc[r][idx] = curr.radars.all[r]?.count || 0
})
return acc
},{})
console.log(res)
console.log(Object.keys(res))