处理树组件需要的数据结构
Apr 25, 2019
基本数据:
1 | const treeData = [ |
处理数据:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22// 找出根节点
const rootTreeData = treeData.filter(item => {
return item.parentId === '0';
})
// 找出根节点后循环添加children
rootTreeData.forEach((root: any) => {
pushChildren(root.id, root)
})
// 处理子节点,判断是否有children,有的话就递归添加children
const pushChildren = (id: string, root: { children: any, hasChild: boolean }) => {
treeData.forEach((item: any) => {
if (root.hasChild && item.parentId === id) {
if (!root.children) {
root.children = [];
}
root.children.push(item)
pushChildren(item.id, item)
}
})
}
最终的数据结构: