I have a tree object with nested nodes and IDs
var data = [
{
id: 'topNode',
parameter: 'parameter',
children: [
{
id: 'node1',
parameter: 'parameter',
children: [
{
id: 'randomNode_1',
parameter: 'parameter'
}],
{
id: 'node2',
parameter: 'parameter'
children: [
{
id: 'randomNode_2',
parameter: 'parameter'
},
{
id: 'randomNode_3',
parameter: 'parameter'
}
]
}
]
}];
I am trying to search the tree for a specific node and return it
This is the method I wrote :
findNodeById(idToFind: string, rootNode: TreeNode): TreeNode {
if (rootNode.getId() === idToFind) {
return rootNode;
} else {
for (const child of rootNode.getChildren()) {
this.findNodeById(idToFind, child);
}
}
}
I call this method:
const foundNode: TreeNode =
this.findNodeById(event.currentTarget.id, this.treeRoot )
Unfortunately, the findNodeById method always returns undefined
Even though I place breakpoints at 'return rootNode;'
I'm stuck at this point and the node being returned is correct
UPDATE : I performed further debugging
- If I add a return statement within the loop
for (const child of rootNode.getChildren()) {
return this.findNodeById(idToFind, child);
}
The method only explores the first branch (node1) to the end, and does not move on to the second one (node2)
- If I remove the return statement in the loop
for (const child of rootNode.getChildren()) {
this.findNodeById(idToFind, child);
}
Once the node is found, the loop continues instead of stopping