I need to recursively navigate through a tree of objects until I find the matching element and push some data into it. Here's a simplified example of my structure:
post.comments = [
{
_id: a,
content: 'Foo',
replies: [
{
_id: aa,
content: 'Foobar',
replies: [
{
_id: aaa,
content: 'Foobarbaz',
replies: [...]
}
]
},
{
_id: ab,
content: 'Barfoo',
replies: [...]
}
]
},
{
_id: b,
content: 'Bar',
replies: [...]
},
{
_id: c,
content: 'Bar',
replies: [...]
},
...
]
The replies can be nested infinitely, in theory.
And here's my recursive function:
function findNode(comments, id, data) {
for (let key in comments) {
currentNode = comments[key]
if (currentNode._id.equals(id)) {
currentNode.replies.push(data)
break;
} else {
if (currentNode.replies.length) {
findNode(currentNode.replies, id, data)
}
else {
continue;
}
}
}
}
findNode(post.comments, id, comment)
This function appears to only read through the child nodes of the first comment object, then exits with 'Cannot read property 'equals' of undefined' when it reaches a node without children (but I presumed that the continue; should pull it out of that branch of the tree?)
What is it I'm not getting about for loops and recursion?
EDIT: Sorry! string.equals(id) comes from Mongoose - it's equivalent to string == id for the puropses of this example array.
currentNodewithletorvaror else it's global.if (currentNode._id == id)?.equalsmethod coming from? A vanilla comparison in JavaScript looks likecomments.id === id.