How to merge each object within arrays by index?

后端 未结 1 1941
无人及你
无人及你 2021-01-25 11:20

How can I merge two arrays of objects of same length?

var array1 = [
  {name: \"lang\", value: \"English\"}, 
  {name: \"age\", value: \"18\"}
];
var array2 = [
         


        
相关标签:
1条回答
  • 2021-01-25 11:51

    A simple map with an Object.assign will do it. Assign unto a new empty object in order to avoid mutating the existing objects.

    var array1 = [
      {name: "lang", value: "English"}, 
      {name: "age", value: "18"}
    ];
    var array2 = [
      {code: "EN", text: "English language"}, 
      {code: "DE", value: "German", text: "German language"}
    ];
    
    var array3 = array1.map((obj, index) => Object.assign({}, obj, array2[index]));
    
    console.log(array3);

    If you have an unknown number of arrays like this:

    const arrays = [
      array1,
      array2,
      array3,
      // …
    ];
    

    then you can use this approach:

    const mergedArray = Array.from({
      length: arrays[0].length
    }, (_, index) => Object.assign({}, ...arrays.map(({[index]: obj}) => obj))));
    

    See this in action with the following example:

    const arrays = [
      [
        {a: 3, b: 5},
        {a: 7, b: 2},
        {a: 1}
      ],
      [
        {b: 8, c: 42},
        {a: 1, b: 12, c: 44},
        {b: 0}
      ],
      [
        {d: 14, e: 15},
        {d: 7},
        {a: 10}
      ]
    ];
    
    console.log(Array.from({
      length: arrays[0].length
    }, (_, index) => Object.assign({}, ...arrays.map(({[index]: obj}) => obj))));

    0 讨论(0)
提交回复
热议问题