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