简体   繁体   English

合并具有相同键的javascript数组值

[英]merge javascript array values with same key

What is the best way to re-organize array into output? 将数组重新组织成输出的最佳方法是什么? I need to merge the values with the same key into an array of objects. 我需要将具有相同键的值合并到对象数组中。

the input array: 输入数组:

 var array = [
    {
      aaa: {
        name: "foo1",
        value: "val1"
      }
    }, 
    { 
      aaa: {
        name: "foo2",
        value: "val2"
      }
    },
    {
     bbb: {
        name: "foo3",
        value: "val3"
      }
    },
    {
      bbb: {
        name: "foo4",
        value: "val4"
      }
    }
];

The desired output: 所需的输出:

var output = [
   { 
    aaa: 
        [{
            name: "foo1",
            value: "val1"
        },{
        name: "foo2",
        value: "val2"
    }]
   },
   {
    bbb: 
        [{
            name: "foo3",
            value: "val3"
        },{
        name: "foo4",
        value: "val4"
    }]
  }

];

What would be the best way to achieve this? 实现这一目标的最佳方法是什么? Thanks in advance. 提前致谢。

You can use reduce 您可以使用reduce

 var array = [{aaa: {name: "foo1",value: "val1"}},{aaa: {name: "foo2",value: "val2"}},{bbb: {name: "foo3",value: "val3"}},{bbb: {name: "foo4",value: "val4"}}]; var newArray = array.reduce((c, v) => { for (var k in v) { c[k] = c[k] || []; c[k].push(v[k]); } return c; }, {}); console.log(newArray); 

Doc: reduce() Doc: reduce()

You can use reduce and forEach function. 您可以使用reduceforEach函数。

 var array = [{ aaa: { name: "foo1", value: "val1" } }, { aaa: { name: "foo2", value: "val2" } }, { bbb: { name: "foo3", value: "val3" } }, { bbb: { name: "foo4", value: "val4" } }]; var result = array.reduce((a, c) => { Object.keys(c).forEach((k) => { if (a[k]) { a[k].push(c[k]); } else { a[k] = [c[k]]; } }) return a; }, {}); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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

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