如何在javascript中将嵌套集合转换为嵌套数组?

2023-12-02

有以下数据。

[
    {"no":1, "name":"ELECTRONICS", "depth":0},
    {"no":2, "name":"TELEVISIONS", "depth":1},
    {"no":3, "name":"TUBE", "depth":2},
    {"no":4, "name":"LCD", "depth":2},
    {"no":5, "name":"PLASMA", "depth":2},
    {"no":6, "name":"PORTABLE ELECTRONICS", "depth":1},
    {"no":7, "name":"MP3 PLAYERS", "depth":2},
    {"no":8, "name":"FLASH", "depth":3},
    {"no":9, "name":"CD PLAYERS", "depth":2},
    {"no":10, "name":"2 WAY RADIOS", "depth":2}
]

我想获取如下数据。

[
    {
        "no":1,
        "name":"ELECTRONICS",
        "depth":0,
        "child_nodes":[
            {
                "no":2,
                "name":"TELEVISIONS",
                "depth":1
                "child_nodes":[
                    {
                        "no":3,
                        "name":"TUBE",
                        "depth":2
                    },
                    ...
                ]
            },
            {
                "no":6,
                "name":"PORTABLE ELECTRONICS",
                "depth":1
                "child_nodes":[ ... ]
            }
        ]
    }
]

我正在递归地尝试它,但效果不好。由于我使用的是babel,所以对于javascript的新功能没有太大的限制。如果您有好主意,请告诉我。谢谢!


您可以对关卡使用辅助数组。

var array = [{ no: 1, name: "ELECTRONICS", depth: 0 }, { no: 2, name: "TELEVISIONS", depth: 1 }, { no: 3, name: "TUBE", depth: 2 }, { no: 4, name: "LCD", depth: 2 }, { no: 5, name: "PLASMA", depth: 2 }, { no: 6, name: "PORTABLE ELECTRONICS", depth: 1 }, { no: 7, name: "MP3 PLAYERS", depth: 2 }, { no: 8, name: "FLASH", depth: 3 }, { no: 9, name: "CD PLAYERS", depth: 2 }, { no: 10, name: "2 WAY RADIOS", depth: 2 }],
    result = [],
    levels = [{ children: result }];

array.forEach(function (o) {
    levels[o.depth].children = levels[o.depth].children || [];
    levels[o.depth].children.push(levels[o.depth + 1] = o);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在javascript中将嵌套集合转换为嵌套数组? 的相关文章

随机推荐