-1

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

//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?

mouchin777
  • 1,428
  • 1
  • 31
  • 59

1 Answers1

2

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)
Karan
  • 12,059
  • 3
  • 24
  • 40