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.map
和Object.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 }] }
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.