You need to enable JavaScript to run this app. 如何在嵌套JSON对象中查询指定id对应的父级id链路数组
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌套JSON对象中查询指定id对应的父级id链路数组

嵌套JSON节点全路径查找实现

需求说明

给定如下嵌套结构的JSON数组,输入目标节点id,返回从根节点到目标节点的完整id路径:

// 原始嵌套数据结构
const treeData = [
  {
    id: 1,
    name: "Mike",
    children: [
      { id: 2, name: "MikeC1" },
      { id: 3, name: "MikeC2" },
      {
        id: 4, name: "MikeC3",
        children: [{ id: 5, name: "MikeCC1" }]
      },
    ]
  },
  {
    id: 6,
    name: "Json",
    children: [
      { id: 7, name: "JsonC1" },
      { id: 8, name: "JsonC2" },
      {
        id: 9, name: "JsonC3",
        children: [{ id: 10, name: "JsonCC1" },{ id: 11, name: "JsonCC2" }]
      },
    ]
  }
]

比如输入id11,期望返回结果为[6,9,11]。

实现代码

通过深度优先搜索+路径回溯的方式实现:

function findParent(targetId, list = treeData, path = []) {
  for (const node of list) {
    // 把当前节点id加入路径
    const currentPath = [...path, node.id]
    // 匹配到目标id直接返回路径
    if (node.id === targetId) {
      return currentPath
    }
    // 有子节点则递归查找
    if (node.children?.length) {
      const findResult = findParent(targetId, node.children, currentPath)
      // 子分支找到结果直接返回
      if (findResult) return findResult
    }
  }
  // 遍历完所有分支未找到返回null
  return null
}

注:代码中?.是ES2020的可选链语法,如果需要兼容低版本JS环境,可替换为if (node.children && node.children.length)。


调用测试

var id = 11
console.log(findParent(id)) // 输出 [6,9,11]

// 其他测试用例
console.log(findParent(5)) // 输出 [1,4,5]
console.log(findParent(2)) // 输出 [1,2]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 11:57:00