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

Given an array of objects, link the child objects to its parents

Lets say I have the following

let arr = 

    [
     {name: "el1", id: 1, parent_id: 0},
     {name: "el2", id: 2, parent_id: 1},
     {name: "el3",  id: 3, parent_id: 0},
     {name: "el4", id: 4, parent_id: 3},
     {name: "el5", id: 5, parent_id: 0},
     {name: "el6", id: 6, parent_id: 2},
    ]

This should result in an arrays as follows

[
 {name: "el1", id: 1, parent_id: 0, childs: [{name: "el2", id: 2, parent_id: 1, childs: [{name: "el6", id: 6, parent_id: 2}]}]},
 {name: "el3",  id: 3, parent_id: 0, childs: [{name: "el4", id: 4, parent_id: 3}},
 {name: "el5", id: 5, parent_id: 0},
]

I can do it for 1 level, but how about multiple leves?
My pseudocode would be something like

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

//iterate the array
//if array[i] has a parent_id != 0, push the element into its corresponding parrent, and delete the pushed index

But how can I do that for infinite potential levels?

>Solution :

Try like below. Explanation is in comments.

let arr = [
     {name: "el1", id: 1, parent_id: 0},
     {name: "el2", id: 2, parent_id: 1},
     {name: "el3",  id: 3, parent_id: 0},
     {name: "el4", id: 4, parent_id: 3},
     {name: "el5", id: 5, parent_id: 0},
     {name: "el6", id: 6, parent_id: 2},
];

function addChild(obj) {
  // get childs and further retrieve its childs with map recursively
  let childs = arr.filter(a => a.parent_id == obj.id).map(addChild);
  
  // if childs are found then add childs in object 
  if (childs.length > 0) {
    return { ...obj, childs };
  }
  
  // if no child found then return object only
  return { ...obj };
}

// get childs for parent id = 0
let result = arr.filter(a => a.parent_id == 0).map(addChild);
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