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

1
  • Can you please share what your code where you were able to do it for 1 level? Commented Mar 10, 2022 at 13:29

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.