You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现递归函数在嵌套节点对象中按名称查找目标节点

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 name matches the nodeName we'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 children array, we loop through each child. For every child, we recursively call searchInNodeByName. If any recursive call returns a non-undefined value (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 undefined to indicate the node doesn't exist in this branch.

This implementation will pass all your test cases:

  • It finds node6 deep in the nested structure
  • It correctly returns undefined for node10 (which doesn't exist)
  • It retrieves node3 along with its tag property as expected

内容的提问来源于stack exchange,提问作者José Antonio Mendoza Chávez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:17:33