最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to merge each object within arrays by index? - Stack Overflow

programmeradmin2浏览0评论

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

var array1 = [
  {name: "lang", value: "English"}, 
  {name: "age", value: "18"}
];
var array2 = [
  {code: "EN", text: "English language"}, 
  {code: "DE", value: "German", text: "German language"}
];

The goal is to create the following array:

var array3 = [
  {name: "lang", value: "English", code: "EN", text: "English language"}, 
  {name: "age", code: "DE", value: "German", text: "German language"}
];

The idea is to create a new array in which array1 is the base and array2 overrides the values if they share the same key, and otherwise adds to the base array. The merging should happen sequentially in the same order that the objects appear in each array.

In this example, the arrays contains two objects, but for my actual situation, I have a couple of dozens of objects.

This is what I’ve been trying to do, but this only merges the first set of objects:

var array3 = Object.assign(array1[0], array2[0]);

How can I loop through it or map it?

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

var array1 = [
  {name: "lang", value: "English"}, 
  {name: "age", value: "18"}
];
var array2 = [
  {code: "EN", text: "English language"}, 
  {code: "DE", value: "German", text: "German language"}
];

The goal is to create the following array:

var array3 = [
  {name: "lang", value: "English", code: "EN", text: "English language"}, 
  {name: "age", code: "DE", value: "German", text: "German language"}
];

The idea is to create a new array in which array1 is the base and array2 overrides the values if they share the same key, and otherwise adds to the base array. The merging should happen sequentially in the same order that the objects appear in each array.

In this example, the arrays contains two objects, but for my actual situation, I have a couple of dozens of objects.

This is what I’ve been trying to do, but this only merges the first set of objects:

var array3 = Object.assign(array1[0], array2[0]);

How can I loop through it or map it?

Share Improve this question edited Jun 19, 2018 at 1:39 Sebastian Simon 19.6k8 gold badges61 silver badges84 bronze badges asked Jun 19, 2018 at 0:41 teebeeteeteebeetee 5491 gold badge8 silver badges23 bronze badges 8
  • Have you written any code so far? Looks like a simple .map or loop would do the trick – CertainPerformance Commented Jun 19, 2018 at 0:42
  • So, you want to by index, merge objects together? – Fallenreaper Commented Jun 19, 2018 at 0:44
  • Possible duplicate of How can I merge properties of two JavaScript objects dynamically? – Fallenreaper Commented Jun 19, 2018 at 0:45
  • @Fallenreaper yeah that is the idea – teebeetee Commented Jun 19, 2018 at 0:48
  • @CertainPerformance i tried manually, but not with map. updated the question – teebeetee Commented Jun 19, 2018 at 0:49
 |  Show 3 more ments

1 Answer 1

Reset to default 6

A simple map with object spread syntax will do it. Instead of object spread, Object.assign can also be used. 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) => ({
    ...obj,
    ...array2[index]
  }));
var array3Alternative = array1.map((obj, index) => Object.assign({}, obj, array2[index]));

console.log(array3);

Note that the order of spread patterns and Object.assign’s arguments matters: latter properties overwrite former properties.

You can also add more properties, e.g. default properties: Object.assign({ code: "XX", value: "Default" }, obj, array2[index]) or ({ code: "XX", value: "Default", ...obj, ...array2[index] }).

If you want to mutate the objects in array1, so that the properties from array2 get added into array1, simply remove the {}, from Object.assign({}, obj, array2[index]). Then it would also be advisable to change the map to a forEach if you’re not expecting to create a resulting variable like 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))));

Note that this also works with arrays of different lengths. The resulting value from accessing a non-existent array index is undefined and spread syntax and Object.assign take care of this by ignoring it. Just make sure to start with the longest array, so the result isn’t missing any objects. This is easier with the snippet where you have an unknown number of arrays (even if it’s always two). Instead of arrays[0].length, you just need to use Math.max(...arrays.map(({ length }) => length)).

发布评论

评论列表(0)

  1. 暂无评论