const array1 = [{id:1,name: "foo"},{id:2,name:"boo"},{id:3,name:"fob"}]
const array2 = [{id:1, carType: "truck"},{id:2, carType: "sedan"},{id:3,carType: "suv"}]
How to push name from array1 to array2 with matching ids
end result
array3 = [
{id:1, carType: "truck",name: "foo"},
{id:2, carType: "sedan", name: "boo"},
{id:3,carType: "suv",name:"fob"}
]
CodePudding user response:
Here's how I'd do it:
const array1 = [{id:1,name: "foo"},{id:2,name:"boo"},{id:3,name:"fob"}]
const array2 = [{id:1, carType: "truck"},{id:2, carType: "sedan"},{id:3,carType: "suv"}]
const indexed = Object.fromEntries(array1.map(o => [o.id, o]))
const combined = array2.map(o => ({...o, ...indexed[o.id]}))
console.log(combined)
i.e. create an object out of one of the arrays, using the id as the key. Then you can map over the 2nd one and use the 'index' to quickly look up elements in the first one.
CodePudding user response:
Index the id
/ name
pairs from array1
then map array2
to a new array with the corresponding values from the index.
const array1 = [{id:1,name: "foo"},{id:2,name:"boo"},{id:3,name:"fob"}];
const array2 = [{id:1,carType:"truck"},{id:2,carType:"sedan"},{id:3,carType:"suv"}];
const nameIndex = array1.reduce(
(hash, { id, name }) => ({
...hash,
[id]: name,
}),
{}
);
const array3 = array2.map((v) => ({
...v,
name: nameIndex[v.id],
}));
console.log(array3);