如何在javascript中将嵌套集转换为嵌套数组? [英] How to convert nested set into nested array in javascript?

查看:155
本文介绍了如何在javascript中将嵌套集转换为嵌套数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下数据.

[
    {"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的新功能没有太大的限制.如果您有个好主意,请告诉我.谢谢!

I'm trying it recursively but it is not good. Since I'm using babel, there is no big restriction on the new function of javascript. If you have a good idea, please let me know. thanks!

推荐答案

您可以为这些级别使用一个辅助数组.

You could use a helper array for the levels.

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; }

这篇关于如何在javascript中将嵌套集转换为嵌套数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆