Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

result:

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

>Solution :

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading