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

在JavaScript/TypeScript中按层级嵌套对象数组的实现方法

Solution to Nest Flat Array by HIERARCHY_LEVEL in JavaScript/TypeScript

Hey there, let's work through turning your flat dataset into a nested hierarchy based on the HIERARCHY_LEVEL field. This implementation assumes your data follows a logical sequence where each entry's level either builds on the previous (e.g., level 1 → level 2 → level 3) or steps back up a level (e.g., level 3 → level 2)—which is typical for such hierarchical data.

Implementation in JavaScript

function nestByHierarchyLevel(dataSet) {
    const result = [];
    // Stack to track the current hierarchy path (each element is a node in the current chain)
    const hierarchyStack = [];

    dataSet.rows.forEach(row => {
        // Create a copy of the row to avoid mutating the original data
        const node = {...row};
        const currentLevel = node.HIERARCHY_LEVEL;

        // Adjust the stack to match the current level: pop elements until we reach the parent level
        while (hierarchyStack.length > 0 && hierarchyStack[hierarchyStack.length - 1].HIERARCHY_LEVEL >= currentLevel) {
            hierarchyStack.pop();
        }

        // Add a children property if it doesn't exist (for parent nodes)
        if (hierarchyStack.length > 0) {
            const parentNode = hierarchyStack[hierarchyStack.length - 1];
            if (!parentNode.children) {
                parentNode.children = [];
            }
            parentNode.children.push(node);
        } else {
            // If stack is empty, this is a top-level (level 1) node
            result.push(node);
        }

        // Push the current node onto the stack to be a parent for subsequent lower levels
        hierarchyStack.push(node);
    });

    return result;
}

// Example usage:
const dataSet = {
    rows: [
        {"ID":0, "Value":10, "HIERARCHY_LEVEL":1},
        {"ID":1, "Value":20, "HIERARCHY_LEVEL":2},
        {"ID":2, "Value":55, "HIERARCHY_LEVEL":3},
        {"ID":3, "Value":77, "HIERARCHY_LEVEL":2},
        {"ID":4, "Value":29, "HIERARCHY_LEVEL":3},
        {"ID":5, "Value":44, "HIERARCHY_LEVEL":4},
        {"ID":6, "Value":34, "HIERARCHY_LEVEL":5},
        {"ID":7, "Value":56, "HIERARCHY_LEVEL":4},
        {"ID":8, "Value":23, "HIERARCHY_LEVEL":2},
        {"ID":9, "Value":23, "HIERARCHY_LEVEL":3}
    ]
};

const nestedData = nestByHierarchyLevel(dataSet);
console.log(JSON.stringify(nestedData, null, 2));

Implementation in TypeScript

If you're using TypeScript, we can add type definitions to make the code type-safe:

// Define types for our data
interface HierarchyNode {
    ID: number;
    Value: number;
    HIERARCHY_LEVEL: number;
    children?: HierarchyNode[];
}

interface DataSet {
    rows: HierarchyNode[];
}

function nestByHierarchyLevel(dataSet: DataSet): HierarchyNode[] {
    const result: HierarchyNode[] = [];
    const hierarchyStack: HierarchyNode[] = [];

    dataSet.rows.forEach(row => {
        const node: HierarchyNode = {...row};
        const currentLevel = node.HIERARCHY_LEVEL;

        while (hierarchyStack.length > 0 && hierarchyStack[hierarchyStack.length - 1].HIERARCHY_LEVEL >= currentLevel) {
            hierarchyStack.pop();
        }

        if (hierarchyStack.length > 0) {
            const parentNode = hierarchyStack[hierarchyStack.length - 1];
            if (!parentNode.children) {
                parentNode.children = [];
            }
            parentNode.children.push(node);
        } else {
            result.push(node);
        }

        hierarchyStack.push(node);
    });

    return result;
}

// Example usage remains similar, with type safety
const dataSet: DataSet = {
    rows: [
        {"ID":0, "Value":10, "HIERARCHY_LEVEL":1},
        {"ID":1, "Value":20, "HIERARCHY_LEVEL":2},
        {"ID":2, "Value":55, "HIERARCHY_LEVEL":3},
        {"ID":3, "Value":77, "HIERARCHY_LEVEL":2},
        {"ID":4, "Value":29, "HIERARCHY_LEVEL":3},
        {"ID":5, "Value":44, "HIERARCHY_LEVEL":4},
        {"ID":6, "Value":34, "HIERARCHY_LEVEL":5},
        {"ID":7, "Value":56, "HIERARCHY_LEVEL":4},
        {"ID":8, "Value":23, "HIERARCHY_LEVEL":2},
        {"ID":9, "Value":23, "HIERARCHY_LEVEL":3}
    ]
};

const nestedData = nestByHierarchyLevel(dataSet);
console.log(JSON.stringify(nestedData, null, 2));

Key Notes

  • Stack Usage: The stack keeps track of the current path in the hierarchy. When we encounter a node with a lower level than the stack's top, we pop elements until we find the correct parent node.
  • Immutability: We create a copy of each row (const node = {...row}) to avoid mutating the original dataset. If mutation is acceptable, you can skip this step.
  • Handling Gaps: This code assumes that the hierarchy levels are sequential (you won't jump from level 1 directly to level 3 without a level 2 node in between). If your data might have such gaps, you'd need to add additional logic to handle missing levels (e.g., create placeholder nodes or adjust the stack logic).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:42:20