Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...