I need to reformat json with a query into a spesific nested format
[
{
"id": 54,
"parent_id": null,
},
{
"id": 55,
"parent_id": 54,
},
{
"id": 56,
"parent_id": 54,
},
{
"id": 57,
"parent_id": 55,
},
{
"id": 58,
"parent_id": 55,
},
{
"id": 59,
"parent_id": 55,
}
]
Im looking for a js algorithm to solve this problem //The above json needs to be in this format: //(not accurate acourding to given data)
[
{
"id": 54,
"children": [
{ "id": 55, "children": [] },
{ "id": 53, "children": [
{ "id": 50, "children": [] }
]
}
]
}
]
I have this script that works but its very in efficient to loop through every instance and child........................................................................................
createDataSet(){
let array = []
let data = this.getData()
data.forEach(level => {
if(level.parent_id === null){
array.push({id: level.id, name: level.name, title: level.name, children: []})
}
});
array.forEach(element => {
data.forEach(level => {
if(level.parent_id === element.id){
element.children.push(
{id: level.id, name: level.name, title: level.name, children: []}
)
}
});
});
array.forEach(element => {
element.children.forEach(child => {
data.forEach(level => {
if(level.parent_id === child.id){
child.children.push(
{id: level.id, name: level.name, title: level.name, children: []}
)
}
})
})
})
array.forEach(element => {
element.children.forEach(child => {
child.children.forEach(granChild => {
data.forEach(level => {
if(level.parent_id === granChild.id){
granChild.children.push(
{id: level.id, name: level.name, title: level.name, children: []}
)
}
})
})
})
})
return array
}