生成树结构数据

复制代码
 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 }
复制代码

 

posted @   冷闲欧巴  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示