1

Let the two arrays be:

const names = [{name: "Bla"}, {name: "BlaBla"}];
const ages= [{age: 15}, {age: 20}];

I Want the new array to be

newArray = [{name: "Bla", age: 15}, {name: "BlaBla", age: 20}]
  • 2
    Hi Mahmoud, welcome to StackOverflow! You will need to add additional details to your question, like what you have tried already, where you are stuck, and so on. – GregL Mar 19 '20 at 23:25
  • You can use `.map()` to loop over one of the arrays, and `Object.assign()` to merge it with the corresponding element of the other array. – Barmar Mar 19 '20 at 23:27
  • Does this answer your question? [Merge 2 arrays of objects](https://stackoverflow.com/questions/7146217/merge-2-arrays-of-objects) – evolutionxbox Mar 19 '20 at 23:48

2 Answers2

3
const names = [{name: "Bla"}, {name: "BlaBla"}];
const ages= [{age: 15}, {age: 20}];
const newArray = [];

let i = 0;

while (names[i] && ages[i]) {
  newArray.push({ ...names[i], ...ages[i] });
  i += 1;
}

console.log(newArray);
dmitrydwhite
  • 776
  • 3
  • 11
3

This is known as the zip operation - for which you can use Array.map() - combined with object merge, either through spread operator or Object.assign().

The callback passed to map() will receive the element and index of an array as its first two arguments respectively; you then use the index to retrieve the value from the other array.

const names = [{name: "Bla"}, {name: "BlaBla"}];
const ages= [{age: 15}, {age: 20}];

result = names.map((name, index) => Object.assign({}, name, ages[index]))

console.log(result)

Note that Object.assign() is used with three arguments, the first one being an empty object; without that, the first argument would get updated in-place as a side effect

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • One thing to be aware of when using `Object.assign()` is that the first parameter is the target object, which is the one that gets modified (mutated). If you didn't want to modify the objects in the names array, you should use `Object.assign({}, name, ages[index])` instead. – GregL Mar 20 '20 at 00:02