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

如何基于ID-ParentId关系为扁平列表节点添加缩进层级标识

解决方案

要给扁平层级列表的每个节点添加indent字段(标识缩进层级),可以按以下步骤实现:

  1. 构建节点映射表:将所有节点存入以id为键的对象,方便通过parentId快速定位父节点,避免重复遍历列表。
  2. 计算节点层级:对每个节点向上追溯父节点,统计层级深度——根节点(parentId为null)的indent为0,子节点的indent是父节点层级+1。
  3. 保留原顺序添加字段:遍历原列表,给每个节点追加计算好的indent字段,维持原有节点顺序不变。

代码实现(JavaScript)

function addIndentToNodes(nodes) {
    // 构建节点映射,快速查找父节点
    const nodeMap = {};
    nodes.forEach(node => {
        nodeMap[node.id] = node;
    });

    // 遍历节点并计算indent
    return nodes.map(node => {
        let indent = 0;
        let currentNode = node;
        // 向上追溯父节点直到根节点
        while (currentNode.parentId !== null && nodeMap[currentNode.parentId]) {
            indent++;
            currentNode = nodeMap[currentNode.parentId];
        }
        return { ...node, indent };
    });
}

// 示例调用
const flatNodes = [
    { id: "100", bezeichnung: "Node 1", parentId: null },
    { id: "101", bezeichnung: "Node 1 A", parentId: "100" },
    { id: "102", bezeichnung: "Node 1 B", parentId: "100" },
    { id: "200", bezeichnung: "Node 2", parentId: null },
    { id: "201", bezeichnung: "Node 2 A", parentId: "200" },
    { id: "202", bezeichnung: "Node 2 B", parentId: "200" },
    { id: "204", bezeichnung: "Node 2 BA", parentId: "202" },
    { id: "203", bezeichnung: "Node 3 A", parentId: "200" }
];

const nodesWithIndent = addIndentToNodes(flatNodes);
console.log(nodesWithIndent);

说明

  • 该方法不依赖节点id的数值规律,即使是UUID也能正常处理。
  • 时间复杂度为O(n*d)(n为节点总数,d为平均层级深度),多数场景下效率足够。
  • 输出结果完全保留原列表的节点顺序,仅新增indent字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:50:25