Brk
Brk

Reputation: 1297

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?

Upvotes: 0

Views: 118

Answers (3)

Lewis
Lewis

Reputation: 14926

You might want to use Array.prototype.map and Object.assign for the merge.

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

Upvotes: 2

void
void

Reputation: 36703

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

Upvotes: 1

Nick D
Nick D

Reputation: 1493

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

Upvotes: 1

Related Questions