当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 将有父子关系的数组对象转换成树形结构数据

将有父子关系的数组对象转换成树形结构数据

2019年02月23日  | 移动技术网IT编程  | 我要评论

原数据:

 1 data: [{
 2     id: 1,
 3     name: '1',
 4 },
 5 {
 6     id: 2,
 7     name: '1-1',
 8     parentid: 1
 9 },
10 {
11     id: 3,
12     name: '1-1-1',
13     parentid: 2
14 },
15 {
16     id: 4,
17     name: '1-2',
18     parentid: 1
19 },
20 {
21     id: 5,
22     name: '1-2-2',
23     parentid: 4
24 },
25 {
26     id: 6,
27     name: '1-1-1-1',
28     parentid: 3
29 },
30 {
31     id: 7,
32     name: '2',
33     parentid: ''
34 },
35 {
36     id: 8,
37     name: '3'
38 },
39 {
40     id: 9,
41     name: '3-1',
42     parentid: 7
43 }
44 ]

转换方法:

 1 /**
 2  * 该方法用于将有父子关系的数组转换成树形结构的数组
 3  * 接收一个具有父子关系的数组作为参数
 4  * 返回一个树形结构的数组
 5  */
 6 translatedatatotree(data) {
 7     // 没有父节点的数据
 8     let parents = data.filter(value => value.parentid == 'undefined' || value.parentid == null ||
 9         value.parentid ==
10         '')
11     // 有父节点的数据
12     let children = data.filter(value => value.parentid !== 'undefined' && value.parentid !=
13         null || value.parentid !=
14         '')
15     // 定义转换方法的具体实现
16     let translator = (parents, children) => {
17         // 遍历父节点数据
18         parents.foreach((parent) => {
19             // 遍历子节点数据
20             children.foreach((current, index) => {
21                 // 此时找到父节点对应的一个子节点
22                 if (current.parentid === parent.id) {
23                     // 对子节点数据进行深复制,这里只支持部分类型的数据深复制,对深复制不了解的童靴可以先去了解下深复制
24                     let temp = json.parse(json.stringify(children))
25                     // 让当前子节点从temp中移除,temp作为新的子节点数据,这里是为了让递归时,子节点的遍历次数更少,如果父子关系的层级越多,越有利
26                     temp.splice(index, 1)
27                     // 让当前子节点作为唯一的父节点,去递归查找其对应的子节点
28                     translator([current], temp)
29                     // 把找到子节点放入父节点的children属性中
30                     typeof parent.children !== 'undefined' ? parent.children
31                         .push(
32                             current) :
33                         parent.children = [current]
34                 }
35             })
36         })
37     }
38     // 调用转换方法
39     translator(parents, children)
40     // 返回最终的结果    
41     return parents;
42 }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网