如何实现递归函数在嵌套节点对象中按名称查找目标节点
Solution for Recursive Node Search in Nested Objects
Let's get that searchInNodeByName function working properly. The core idea is to check the current node first, then recursively traverse any child nodes until we find a match or exhaust all possibilities. Here's the completed function:
const searchInNodeByName = (node, nodeName) => { // First, check if the current node matches the target name if (node.name === nodeName) { return node; } // If the node has children (and it's an array), traverse each child if (Array.isArray(node.children)) { for (const child of node.children) { const foundNode = searchInNodeByName(child, nodeName); // If we found the node in this child branch, return it immediately if (foundNode) { return foundNode; } } } // If no match found in current node or its children, return undefined return undefined; };
How this works:
- Base Case 1: We first check if the current node's
namematches thenodeNamewe're searching for. If it does, we return the node right away—this stops the recursion and sends the found node back up the call stack. - Recursive Traversal: If the current node has a
childrenarray, we loop through each child. For every child, we recursively callsearchInNodeByName. If any recursive call returns a non-undefinedvalue (meaning we found the target node in that branch), we return that node immediately to avoid unnecessary extra checks. - Base Case 2: If we've checked the current node and all its children without finding a match, we return
undefinedto indicate the node doesn't exist in this branch.
This implementation will pass all your test cases:
- It finds
node6deep in the nested structure - It correctly returns
undefinedfornode10(which doesn't exist) - It retrieves
node3along with itstagproperty as expected
内容的提问来源于stack exchange,提问作者José Antonio Mendoza Chávez
相关产品推荐
相关产品推荐

