列表与树
ts
interface TreeNode {
id: string;
parentId?: string;
children?: TreeNode[];
[key: string]: any;
}
interface FlatNode extends TreeNode {
ancestors: TreeNode[];
}
// 压平树结构为一个列表
function flattenTree(tree: TreeNode[], ancestors: TreeNode[] = []): FlatNode[] {
return tree.reduce((list: FlatNode[], node: TreeNode) => {
const nodeWithAncestors = {
...node,
ancestors: [...ancestors]
};
const children = node.children || [];
return list.concat(nodeWithAncestors, flattenTree(children, [...ancestors, nodeWithAncestors]));
}, []);
}
// 回显列表为树结构
function restoreTree(list: FlatNode[], rootId?: string): TreeNode[] {
const map = new Map<string, TreeNode>();
list.forEach(node => {
node.children = [];
map.set(node.id, node);
});
list.forEach(node => {
const parent = map.get(node.parentId!);
if (parent) {
parent.children!.push(node);
}
});
return list.filter(node => !node.parentId || node.parentId === rootId) as TreeNode[];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38