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?