Search code examples
javascriptarraysmultidimensional-arraydepthnested-sets

How to convert nested set into nested array in javascript?


There is following data.

[
    {"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}
]

I want to get data like below.

[
    {
        "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":[ ... ]
            }
        ]
    }
]

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!


Solution

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