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

如何将任意层级的扁平结构数组转换为树形结构?

扁平结构数组转树形结构的可扩展实现

需求说明

需要将包含层级字段(如lvl1、lvl2……lvlN)的扁平数组转换为嵌套树形结构,支持任意数量的层级,无需针对固定层级编写硬编码逻辑。

输入示例

const input = [
    {
        lvl1:"Code1",
        lvl2:"Type1",
        lvl3:"Desc1",
        lvl4:"Check1"
    },
    {
        lvl1:"Code1",
        lvl2:"Type1",
        lvl3:"Desc1",
        lvl4:"Check2"
    },
    {
        lvl1:"Code2",
        lvl2:"Type2",
        lvl3:"Desc2",
        lvl4:"Check1"
    },
];

预期输出

[
    {
        "level_key": "lvl1",
        "level_value": "Code1",
        "children": [
            {
                "level_key": "lvl2",
                "level_value": "Type1",
                "children": [
                    {
                        "level_key": "lvl3",
                        "level_value": "Desc1",
                        "children": [
                            {
                                "level_key": "lvl4",
                                "level_value": "Check1",
                                "children": []
                            },
                            {
                                "level_key": "lvl4",
                                "level_value": "Check2",
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "level_key": "lvl1",
        "level_value": "Code2",
        "children": [
            {
                "level_key": "lvl2",
                "level_value": "Type2",
                "children": [
                    {
                        "level_key": "lvl3",
                        "level_value": "Desc2",
                        "children": [
                            {
                                "level_key": "lvl4",
                                "level_value": "Check1",
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

可扩展实现方案

以下是一个通用的JavaScript实现,自动识别所有层级字段并构建树形结构:

function flatToTree(flatArray) {
    const tree = [];

    flatArray.forEach(item => {
        // 提取所有层级键并按数字排序(确保lvl1 → lvl2 → ... → lvlN的顺序)
        const levelKeys = Object.keys(item)
            .filter(key => key.startsWith('lvl'))
            .sort((a, b) => parseInt(a.slice(3)) - parseInt(b.slice(3)));
        
        let currentNodeList = tree;

        levelKeys.forEach(key => {
            const value = item[key];
            // 在当前层级查找是否已存在对应节点
            let targetNode = currentNodeList.find(node => 
                node.level_key === key && node.level_value === value
            );

            // 如果不存在则创建新节点并加入当前层级
            if (!targetNode) {
                targetNode = {
                    level_key: key,
                    level_value: value,
                    children: []
                };
                currentNodeList.push(targetNode);
            }

            // 进入下一层级继续处理
            currentNodeList = targetNode.children;
        });
    });

    return tree;
}

实现优势

  • 完全可扩展:无需修改代码即可支持任意数量的层级(如lvl5、lvl6等),只要层级字段命名符合lvl+数字的规则
  • 高效简洁:通过两次遍历(外层遍历扁平数组,内层遍历单条数据的层级字段)完成构建,时间复杂度为O(n*m)(n为数组长度,m为单条数据的层级数)
  • 通用性强:只要输入数据的层级字段命名统一,就能直接复用该函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:30:43