生成树结构数据

 1 /**
 2  * 构造树型结构数据
 3  * @param {*} data 数据源
 4  * @param {*} id id字段 默认 'id'
 5  * @param {*} parentId 父节点字段 默认 'parentId'
 6  * @param {*} children 孩子节点字段 默认 'children'
 7  */
 8 export function handleTree(data, id, parentId, children) {
 9     let config = {
10         id: id || 'id',
11         parentId: parentId || 'parentId',
12         childrenList: children || 'children'
13     };
14 
15     var childrenListMap = {};
16     var nodeIds = {};
17     var tree = [];
18 
19     for (let d of data) {
20         let parentId = d[config.parentId];
21         if (childrenListMap[parentId] == null) {
22             childrenListMap[parentId] = [];
23         }
24         nodeIds[d[config.id]] = d;
25         childrenListMap[parentId].push(d);
26     }
27 
28     for (let d of data) {
29         let parentId = d[config.parentId];
30         if (nodeIds[parentId] == null) {
31             tree.push(d);
32         }
33     }
34 
35     for (let t of tree) {
36         adaptToChildrenList(t);
37     }
38 
39     function adaptToChildrenList(o) {
40         if (childrenListMap[o[config.id]] !== null) {
41             o[config.childrenList] = childrenListMap[o[config.id]];
42         }
43         if (o[config.childrenList]) {
44             for (let c of o[config.childrenList]) {
45                 adaptToChildrenList(c);
46             }
47         }
48     }
49     return tree;
50 }

 

上一篇:Java开发之JDK 开发环境配置


下一篇:根据ParentId生成树状结构这po事