Skip to content
Advertisement

Comparing two nested arrays of objects, and exclude the elements who match values by “id” into new array in JS

I have two arrays of objects, i need to match arr2 names to arr1 by matching id’s

Advertisement

Answer

You could create a Map from arr2, keyed by id and with as value the corresponding object.

Then map arr1, looking up the object in the Map, both for the object itself and the children:

let arr1 = [{id:1,children:[9]},{id:2,children:[]},{id:14,children:[3,42]},];
let arr2 = [{id:1,name:"name1"},{id:2,name:"name2"},{id:3,name:"name3"},{id:9,name:"name9"},{id:14,name:"name14"},{id:42,name:"name42"},{id:100,name:"idNotMatch"}];

const map = new Map(arr2.map(o => [o.id, o]));
const result = arr1.map(o => 
    Object.assign(o, {
        ...map.get(o.id),
        children: o.children.map(id => map.get(id))
    })
);

console.log(result);
Advertisement