-1

I have a tough requirement needed your advises.

I have 2 arrays:

var array1 = [{ 'x': 1, 'z': 2 }, { 'x': 2, 'z': 1 }];
var array2 = [{ 'x': 1, 'y': 1 }, { 'x': 2, 'y': 3 }];

Requirement: merge 2 array into one with format:

[{ 'x': 1, 'y': 1, 'z': 2 }, { 'x': 2, 'y': 3 , 'z': 1 }]

I have gone through lodash library, features like 'merge' or 'union' don't serve for this purpose.

Any solutions are welcomed and appreciated

franco phong
  • 2,219
  • 3
  • 26
  • 43
  • What have you tried so far? This looks like a homework task to me... – Danmoreng Jun 14 '18 at 14:59
  • My point is for the large array, about 10000 items. I can use loop logic to achieve it, but if any best practice, please share it. – franco phong Jun 14 '18 at 15:01
  • 1
    Seems to me as though you should just use a simple loop. I see no other way from what libraries I'm familiar with. For that matter, if there are any libraries for the task, they'll just use loops too. – octacian Jun 14 '18 at 15:03
  • @francophong nobody here is engaging in hate speech (I guess it's not the word you actually meant to use, as you don't seem to be a native English speaker (EDIT: just an assumption, I see you're from the UK but your name suggested otherwise. if that's not the case it's even worse :P)). The other users just pointed out it looked like homework and suggested to just use a loop. – Federico klez Culloca Jun 14 '18 at 15:16
  • Thanks for comments @Federico – franco phong Jun 14 '18 at 15:22

2 Answers2

1

Try following

var array1 = [{ 'x': 1, 'z': 2 }, { 'x': 2, 'z': 1 }];
var array2 = [{ 'x': 1, 'y': 1 }, { 'x': 2, 'y': 3 }];

let result = array1.map((o,i) => ({...o, ...array2[i]}));
console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

You could map with Object.assign for new objects.

var array1 = [{ 'x': 1, 'z': 2 }, { 'x': 2, 'z': 1 }],
    array2 = [{ 'x': 1, 'y': 1 }, { 'x': 2, 'y': 3 }],
    result = array1.map((o,i) => Object.assign(o, array2[i]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392