Trying to work out the most performant way to merge objects from two arrays (that share an id) into a brand new array of the same length of the original two arrays.
For example:
// Merge these two arrays
const arrayOne = [
{ id: 34560, name: "John" },
{ id: 23123, name: "Jake" },
{ id: 11023, name: "Peter" },
{ id: 29221, name: "Sara" }
];
const arrayTwo = [
{ id: 34560, age: 24 },
{ id: 23123, age: 30 },
{ id: 11023, age: 19 },
{ id: 29221, age: 20 }
];
// Into this array
const merged = [
{ id: 34560, name: "John", age: 24 },
{ id: 23123, name: "Jake", age: 30 },
{ id: 11023, name: "Peter", age: 19 },
{ id: 29221, name: "Sara", age: 20 }
];
This is what I've got so far:
const mergedArray = [];
arrayOne.forEach(x => {
arrayTwo.forEach(y => {
if (x.id === y.id) {
mergedArray.push(Object.assign(x, y));
}
})
})
Any help is appreciated. Thanks in advance.