Skip to content

在树中查找指定id找到所有直属父级节点id

javascript
let list = [
  {
    "id": 1291,
    "parentId": 0,
    "name": "华中科技大学",
    "children": [
      {
        "id": 1,
        "parentId": 1291,
        "name": "理学",
        "children": [
          {
            "id": 1611,
            "parentId": 1,
            "name": "生物学",
            "children": [], // children支持空数值和null值
          }
        ],
      },
      {
        "id": 2,
        "parentId": 1291,
        "name": "工学",
        "children": [
          {
            "id": 1612,
            "parentId": 2,
            "name": "生物与医药",
            "children": [],
          }
        ]
      },
      {
        "id": 3,
        "parentId": 1291,
        "name": "学科门类",
        "children": [
          {
            "id": 1629,
            "parentId": 3,
            "name": "报考专业",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": 1292,
    "parentId": 0,
    "name": "东北林业大学",
    "children": [
      {
        "id": 4,
        "parentId": 1292,
        "name": "理学",
        "children": [
          {
            "id": 1613,
            "parentId": 4,
            "name": "生物学",
            "children": []
          },
          {
            "id": 1614,
            "parentId": 4,
            "name": "生物学",
            "children": []
          }
        ]
      },
      {
        "id": 5,
        "parentId": 1292,
        "name": "工学",
        "children": [
          {
            "id": 1615,
            "parentId": 5,
            "name": "生物与医药",
            "children": []
          },
          {
            "id": 1616,
            "parentId": 5,
            "name": "生物与医药",
            "children": []
              },
                    {
                        "id": 1621,
                        "parentId": 5,
                        "name": "生物与医药",
                        "children": []
                    }
                ]
            }
        ]
    }
]

// 递归追溯父级节点
function findParentIds(data, parentKey, id) {
    let path = [];
    let currentNode = findNodeById(data, id);
    while (currentNode && currentNode[parentKey] !== 0) {
        path.push(currentNode[parentKey]);
        currentNode = findNodeById(data, currentNode[parentKey]);
    }

    // 递归查找节点
    function findNodeById(data, id) {
        for (let node of data) {
            if (node.id === id) {
                return node;
            }
            if (node.children) {
                let result = findNodeById(node.children, id);
                if (result) return result;
            }
        }
        return null;
    }
    return path.reverse(); // 从根到目标节点的顺序
}

// 获取结果
let parentIds = findParentIds(list, 'parentId', 1616);
console.log(parentIds); // [1292, 5]

基于 MIT 许可发布