简体   繁体   English

如何使用 JavaScript 从数组创建动态树?

[英]How to create a dynamic tree using JavaScript from an Array?

I have an array let say A[A.A1.A2,A.A1.A3,A.B1.B2,B.B1.B2,C.C1.C2]我有一个数组,比如说A[A.A1.A2,A.A1.A3,A.B1.B2,B.B1.B2,C.C1.C2]

Now I have to create a Tree Structure like following using javascript现在我必须创建一个树结构,如下所示使用 javascript

A
  A1
     A2
     A3
  B1
     B2
B1
  B1
    B2
C
  C1
    C2

Can anybody give me some idea how to do that?任何人都可以给我一些想法如何做到这一点?

Regards, Pankaj问候, 潘卡吉

You can iterate over the strings, split them, store the items and then iterate over all items by checking if the previous data set has the same value .您可以遍历字符串、拆分它们、存储项目,然后通过检查之前的数据集是否具有相同的值来遍历所有项目。 If not , assign a new node and store the next level in the levels array.如果不是,则分配一个新节点并将下一个级别存储在levels数组中。

Then, replace last with the temp array.然后,用temp数组替换last

The main logic is wrapped in a helper array, which stores the last inserted nodes of the level.主要逻辑被包装在一个辅助数组中,该数组存储了关卡最后插入的节点。 This requires a sorted data set.这需要一个排序的数据集。

 var array = ['A.A1.A2', 'A.A1.A3', 'A.B1.B2', 'B.B1.B2', 'C.C1.C2'], tree = [], levels = [tree], last = []; array.forEach(s => { var temp = s.split('.'); temp.forEach((name, i) => { if (last[i] === name) return; levels[i].push({ name, children: levels[i + 1] = [] }); }); last = temp; }); console.log(tree);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM