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

如何根据ID在嵌套对象中查找并返回完整分支树?

解决方案

要实现根据ID查找并返回完整分支的需求,我们可以通过递归遍历节点,构建从根到目标节点的路径结构,同时保留目标节点的所有子元素。以下是修改后的实现代码:

function findCompleteBranch(data, targetId) {
  // 处理输入为数组的场景
  if (Array.isArray(data)) {
    for (const item of data) {
      const result = findCompleteBranch(item, targetId);
      if (result) {
        return [result];
      }
    }
    return null;
  }

  // 当前节点匹配目标ID,直接返回该节点的拷贝(保留所有子元素)
  if (data.id === targetId) {
    return {...data};
  }

  // 递归遍历子节点查找匹配项
  if (data.children?.length) {
    let matchedChild;
    for (const child of data.children) {
      matchedChild = findCompleteBranch(child, targetId);
      if (matchedChild) break;
    }

    // 找到匹配的子分支,构建当前节点的拷贝并替换children为匹配分支
    if (matchedChild) {
      return {...data, children: [matchedChild]};
    }
  }

  // 未找到匹配,返回null
  return null;
}

代码逻辑说明

  1. 输入兼容:先判断输入是否为数组,遍历数组中的每个元素进行查找,确保同时支持单个对象或数组作为输入。
  2. 节点匹配判断:如果当前节点ID与目标ID一致,直接返回该节点的浅拷贝(保留所有属性,包括子节点)。
  3. 递归查找子节点:如果当前节点有子节点,逐个递归查找;一旦找到匹配的子分支,就复制当前节点,并将其children替换为这个匹配的子分支,从而保留从根到目标节点的路径。
  4. 无匹配处理:遍历完所有节点都未找到匹配时,返回null。

测试示例

示例1:查找ID=1006

const data = {
  "id": 85,
  "title": "Objects",
  "address": "i=85",
  "children": [
    {
      "id": "85/0:Simulation",
      "title": "Simulation",
      "parent": "Objects",
      "address": "ns=3;s=85/0:Simulation",
      "children": [
        { "id": 1001, "title": "Constant", "parent": "Simulation", "address": "ns=3;i=1001" },
        { "id": 1002, "title": "Counter", "parent": "Simulation", "address": "ns=3;i=1002" },
        { "id": 1003, "title": "Random", "parent": "Simulation", "address": "ns=3;i=1003" },
        { "id": 1004, "title": "Sawtooth", "parent": "Simulation", "address": "ns=3;i=1004" },
        { "id": 1005, "title": "Sinusoid", "parent": "Simulation", "address": "ns=3;i=1005" },
        { "id": 1006, "title": "Square", "parent": "Simulation", "address": "ns=3;i=1006" },
        { "id": 1007, "title": "Triangle", "parent": "Simulation", "address": "ns=3;i=1007" }
      ]
    }
  ]
};

console.log(findCompleteBranch(data, 1006));

输出结果:

{
  "id": 85,
  "title": "Objects",
  "address": "i=85",
  "children": [
    {
      "id": "85/0:Simulation",
      "title": "Simulation",
      "parent": "Objects",
      "address": "ns=3;s=85/0:Simulation",
      "children": [
        {
          "id": 1006,
          "title": "Square",
          "parent": "Simulation",
          "address": "ns=3;i=1006"
        }
      ]
    }
  ]
}

示例2:查找ID="85/0:Simulation"

console.log(findCompleteBranch(data, "85/0:Simulation"));

输出结果为包含该节点及其所有子元素的完整分支,即原数据中Objects节点下仅保留Simulation子节点,且Simulation的所有子节点都被完整保留。

内容的提问来源于stack exchange,提问作者zaxarhic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:44:50