Reputation: 443
I need to transform an array of object into new array based on the parent_id's in the list. In the below given input we have a parent_id which tells use parent of the given object.
Input:
[
{
"id": 1,
"title": "Item 1",
"parent_id": null
},
{
"id": 2,
"title": "Item 2",
"parent_id": 1
},
{
"id": 3,
"title": "Item 3",
"parent_id": 2
},
{
"id": 4,
"title": "Item 4",
"parent_id": null
},
{
"id": 5,
"title": "Item 5",
"parent_id": null
},
{
"id": 6,
"title": "Item 6",
"parent_id": 5
},
{
"id": 7,
"title": "Item 7",
"parent_id": 6
},
{
"id": 8,
"title": "Item 8",
"parent_id": 6
}
]
Desired Output:
[
{
"id": 1,
"title": "Item 1",
"parent_id": null,
"child": [{
"id": 2,
"title": "Item 2",
"parent_id": 1,
"child": [{
"id": 3,
"title": "Item 3",
"parent_id": 2
}]
}]
},
{
"id": 4,
"title": "Item 4",
"parent_id": null
},
{
"id": 5,
"title": "Item 5",
"parent_id": null,
"child": [{
"id": 6,
"title": "Item 6",
"parent_id": 5,
"child": [{
"id": 7,
"title": "Item 7",
"parent_id": 6
}, {
"id": 8,
"title": "Item 8",
"parent_id": 6
}]
}]
}
]
In the desired output I have created a nested array of object where each object will hold its children. Can someone please suggest how we can do this in javascript?
Upvotes: 1
Views: 911
Reputation: 386604
Just take a loop and build a tree with the help of an object.
var data = [{ id: 1, title: "Item 1", parent_id: null }, { id: 2, title: "Item 2", parent_id: 1 }, { id: 3, title: "Item 3", parent_id: 2 }, { id: 4, title: "Item 4", parent_id: null }, { id: 5, title: "Item 5", parent_id: null }, { id: 6, title: "Item 6", parent_id: 5 }, { id: 7, title: "Item 7", parent_id: 6 }, { id: 8, title: "Item 8", parent_id: 6 }],
tree = function (data, root) {
var t = {};
data.forEach(o => {
Object.assign(t[o.id] = t[o.id] || {}, o);
t[o.parent_id] = t[o.parent_id] || {};
t[o.parent_id].children = t[o.parent_id].children || [];
t[o.parent_id].children.push(t[o.id]);
});
return t[root].children;
}(data, null);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1