简体   繁体   中英

Merge 2 arrays of JavaScript objects

Lets say I have 2 arrays of objects and I want to merge their objects in parallel manner. For example

var array = [{foo: 2} , {boo: 3}]
var array2 = [{foo2: 2}, {boo2: 4}]

The result will be

var array3 = [{foo:2,foo2:2},{boo:3,boo2:4}]

How can I do it in javascript?

您可能要使用Array.prototype.mapObject.assign进行合并。

array.map((obj,index) => Object.assign(obj,array2[index]));

You should look a lodash:

 var users = { 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] }; var ages = { 'data': [{ 'age': 36 }, { 'age': 40 }] }; _.merge(users, ages); // → { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } 

Lodash doc for merge

You can traverse through one array and pick one item and pick the item from the another array and then merge them.

 var array = [{foo: 2} , {boo: 3}]; var array2 = [{foo2: 2}, {boo2: 4}]; var _o = array.map(function(obj1, i){ var obj2 = array2[i]; for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } return obj1; }); // _o is the final array alert(JSON.stringify(_o)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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