Skip to content

Commit a1973bf

Browse files
author
Bruce
committed
add tree
1 parent 6b50bc3 commit a1973bf

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

+31
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,35 @@ handleArrayToEnum(data, 'jobId', 'jobName')
4444
"168503524182190": "到这点包引克"
4545
}
4646
*/
47+
```
48+
49+
3. 生成树结构
50+
```
51+
// 生成树
52+
const toTree = (data: any, value = 'id', pid = 'pid', children = 'children') => {
53+
// 删除所有children,以防止多次调用
54+
data.forEach((item: any) => {
55+
delete item[children];
56+
});
57+
58+
// 将数据存储为以id为 KEY 的 map 索引数据列
59+
const map: any = {};
60+
data.forEach((item: any) => {
61+
map[item[value]] = item;
62+
});
63+
64+
const val: any = [];
65+
data.forEach((item: any) => {
66+
// 以当前遍历项的pid,去map对象中找到索引的id
67+
const parent = map[item[pid]];
68+
// 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
69+
if (parent) {
70+
(parent.children || (parent.children = [])).push(item);
71+
} else {
72+
//如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
73+
val.push(item);
74+
}
75+
});
76+
return val;
77+
},
4778
```

0 commit comments

Comments
 (0)