简体   繁体   English

JavaScript 创建对象结构数组

[英]JavaScript create array of Object structure

Here is my problem:这是我的问题:

I have a JSON structure as below我有一个 JSON 结构如下

[{
    "groupid": 29,
    "percentage": 14
}, {
    "groupid": 29,
    "percentage": 22
}, {
    "groupid": 59,
    "percentage": 66,
}]

and i need to convert that into as below using Javascript.我需要使用 Javascript 将其转换为如下所示。

{
    "29": [14, 22],
    "59": [66]
}

reduce the input into an object. reduce对对象的输入。 On each iteration, create an array at the groupid key in the accumulator object if it doesn't exist yet, and then push to the array:在每次迭代中,如果累加器对象中的groupid键尚不存在,则在该数组中创建一个数组,然后push送到该数组:

 const input = [{ "groupid": 29, "percentage": 14 }, { "groupid": 29, "percentage": 22 }, { "groupid": 59, "percentage": 66, }]; const output = input.reduce((a, { groupid, percentage }) => { if (!a[groupid]) a[groupid] = []; a[groupid].push(percentage); return a; }, {}); console.log(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM