The tree structure looks like this -
const init = [
{
name: 'A',
children: [
{
name: 'A1',
children: []
},
{
name: 'A2',
children: [
{
name: 'A21',
children: []
}
]
}
]
},
{
name: 'B',
children: [
{
name: 'B1',
children: []
},
{
name: 'B2',
children: []
}
]
}
]
And I have variables
currentPath = ['A', 'A2', 'A21']node = { name: 'A211', children: [] }
I want to transform init to
const init = [
{
name: 'A',
children: [
{
name: 'A1',
children: []
},
{
name: 'A2',
children: [
{
name: 'A21',
children: [
{
name: 'A211',
children: []
}
]
}
]
}
]
},
{
name: 'B',
children: [
{
name: 'B1',
children: []
},
{
name: 'B2',
children: []
}
]
}
]
Please tell me what is the function that I need to use funcAppendNode(init, currentPath, node) that takes init, the currentPath and the new node and returns the new init. I assume it has something to do with recursion but I am unable to succeed.
Here is what I've tried so far.
const funcAppend = (init, currentPath, node) => {
let newState = [...init]
for (let i = 1; i < currentPath.length; i++) {
newState = newState.find(o => o.name === currentPath[i]).children
}
newState.push(node)
return newState
}
The above function is returning
[ { name: 'A211', children: [] } ]
Please help.