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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在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的新功能没有很大的限制。如果你有个好主意,请告诉我。谢谢!

答案

您可以为级别使用辅助数组。

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; 
另一答案
//The trees root = our expected result  
 const result = [];
 var acc  =  depth: -1, children: result;

 for(const el of data)
   //walk upwards in the tree
   var up = acc.depth - el.depth + 1 ;
   while(up--) acc = acc.parent 
   //walk down and add the current el as a child
   el.parent = acc;
   (acc.children || (acc.children = [])).push(el);
   acc = el;


console.log(result);

您可以只穿过一棵树(acc)并将父母/孩子联系在一起。

以上是关于如何在javascript中将嵌套集转换为嵌套数组?的主要内容,如果未能解决你的问题,请参考以下文章

在Javascript中将数组转换为嵌套的JSON?

如何在 Swift 中将单个数组转换为嵌套数组? [复制]

如何在python,dataframe中将数据转换为嵌套字典

PHP将单维数组转换为嵌套数组

如何在 C# 中将嵌套列表转换为 XML

如何在python中将展平表转换为嵌套(分层)json?