【发布时间】:2017-01-20 00:56:50
【问题描述】:
如何使用以下数据属性通过嵌套无序列表 (<ul>) 呈现树形视图?
// parentId value is always 0 for root nodes, otherwise this value corresponds to the id of its parent
// sequence represents the order of the element in the branch
// level represents the tree level of the element, root nodes will have a level of 1
var data = [
{ id: 'K66', level: 1, name: 'B', parentId: '0', sequence: 2 },
{ id: 'K65', level: 1, name: 'A', parentId: '0', sequence: 1 },
{ id: 'KK2', level: 2, name: 'Alan', parentId: 'K65', sequence: 1 },
{ id: 'KK22', level: 2, name: 'Bir', parentId: 'K66', sequence: 1 },
{ id: 'KK92', level: 2, name: 'Abe', parentId: 'K65', sequence: 2 },
{ id: 'KK77', level: 3, name: 'Boromir', parentId: 'KK22', sequence: 1 }
];
结果应如下所示:
A
Alan
Abe
B
Bir
Boromir
我尝试过使用 for 循环,但很快我就重复代码来获取子节点,但无法将其重构为递归函数。
这是一个包含数据的 CodePen:http://codepen.io/nunoarruda/pen/KgVPmv
【问题讨论】:
-
您是否在 SO 上搜索过“Javascript 渲染树”?有一些现有的解决方案。您尚未发布您的编码尝试 (MCVE),这可能会影响您的回复率。
-
@nunoarruda ...不需要递归方法。看看我下面的答案。
标签: javascript data-structures tree iteration reduce