'Given an array of objects, link the child objects to its parents [duplicate]
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?
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karan |
