I am trying to return a specific node in a JSON object structure which looks like this
{
"id":"0",
"children":[
{
"id":"1",
"children":[...]
},
{
"id":"2",
"children":[...]
}
]
}
So it's a tree-like child-parent relation. Every node has a unique ID. I'm trying to find a specific node like this
function findNode(id, currentNode) {
if (id == currentNode.id) {
return currentNode;
} else {
currentNode.children.forEach(function (currentChild) {
findNode(id, currentChild);
});
}
}
I execute the search for example by findNode("10", rootNode)
. But even though the search finds a match the function always returns undefined
. I have a bad feeling that the recursive function doesn't stop after finding the match and continues running an finally returns undefined
because in the latter recursive executions it doesn't reach a return point, but I'm not sure how to fix this.
Please help!
See Question&Answers more detail:os