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

时间:2017-12-25 13:56:57

标签: javascript arrays multidimensional-array depth nested-sets

有以下数据。

<div *ngIf="finaldata; let L">

</div>

我想获得如下数据。

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

我正在尝试递归,但这并不好。由于我使用的是babel,因此对javascript的新功能没有很大的限制。如果你有个好主意,请告诉我。谢谢!

2 个答案:

答案 0 :(得分:6)

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

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

//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)并将父母/孩子联系在一起。