In the tree object I'm working with, a node may have a 'children' property that can contain an array of child nodes. It's a concept for a multilevel menu structure.
What I'd like to achieve is to dynamically add a reference to the parent in the children.
I'm stuck at the point where I should mutate the original object. I cannot figure out how to do that properly.
The code snippet begins with an example object. It is followed by a recursive function that visits every node and holds reference to the parent, but does not modify the object. Then there is a function that modifies the object, but to only 3 levels in depth.
var obj = {
id: "a",
children: [{
id: "b",
children: [{
id: "c"
}]
},
{
id: "d"
}
]
};
function visitNode(node, parent) {
if (node.children) {
console.log('node with children', node, 'parent\'s ID is:', parent.id);
node.children.forEach(child => visitNode(child, node));
} else {
console.log('node with no children:', node, 'parent\'s ID is:', parent.id);
}
}
visitNode(obj, {id: null});
function mutate(obj) {
obj.parentId = null;
if (obj.children) {
obj.children.forEach((child, i) => {
obj.children[i].parentId = obj.id;
if (child.children) {
child.children.forEach((child2, j) => {
obj.children[i].children[j].parentId = obj.children[i].id;
})
}
})
}
}
mutate(obj);
console.log('mutated object', obj);