Following is my array
[
{id: 1, title: 'hello', parent: {number:0}},
{id: 2, title: 'hello', parent: {number:0}},
{id: 3, title: 'hello', parent: {number:1}},
{id: 4, title: 'hello', parent: {number:3}},
{id: 5, title: 'hello', parent: {number:4}},
{id: 6, title: 'hello', parent: {number:4}},
{id: 7, title: 'hello', parent: {number:3}},
{id: 8, title: 'hello', parent: {number:2}}
]
and I want to have objects nested like this as output :
[
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2}
]}
]
Please help me with a recursive function to do this in node.js.
Following is the recursive function is what I have tried:
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].parent.number == parent.number) {
var children = getNestedChildren(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
Please help me to solve this. I am a newbie in this.