0

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?

0

3 Answers 3

2

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

array.map((obj,index) => Object.assign(obj,array2[index]));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

2 Comments

of course, but you need to implement it yourself then
then why lodash? As OP doesn't tagged lodash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.