扁平数据和树状数据结构的互相转换

扁平结构转换成树状结构

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
const list = [
{ id: 1, parentId: null },
{ id: 2, parentId: null },
{ id: 12, parentId: 1 },
];

function bullTree (list) {
const temp = {};
const tree = [];
for (let item of list) {
temp[item.id] = item;
}
for (let i in temp) {
// 当前节点
const currentNode = temp[i];
if (currentNode.parentId) {
// 非顶层节点
const currentParentNode = temp[currentNode.parentId];
if (currentParentNode) {
// 当前节点的父节点存在
if (!currentParentNode.children) {
currentParentNode.children = [];
}
currentParentNode.children.push(currentNode);
}
} else {
// 顶层节点
tree.push(currentNode);
}
}
}

树状结构转换成扁平结构

这里用到了递归的方式。

1
2
3
4
5
6
7
8
9
10
11
function buildList (tree) {
let list = [];
tree.forEach((item) => {
const [ children, ...rest ] = item;
list.push(rest);
if (children) {
list = list.concat(buildList(children));
}
});
return list;
}