-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
49 lines (37 loc) · 1.33 KB
/
index.js
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
39
40
41
42
43
44
45
46
47
48
49
/*
使用队列实现遍历
*/
function hasParentNode(data, item, nodeUniqueIndex, nodeLinkKey) { // 是否存在父节点
const index = data.findIndex(c => c[nodeUniqueIndex] === item[nodeLinkKey]);
return ~index;
}
function getChildrenNodes(parentNodes, allNodes, nodeUniqueIndex, nodeLinkKey) { // 获取每一个节点的子节点
if (!parentNodes.length) return;
const node = parentNodes.shift();
for (let i = 0; i < allNodes.length; i += 1) {
const current = allNodes[i];
if (node[nodeUniqueIndex] === current[nodeLinkKey]) {
if (node.children) {
node.children.push(current);
} else {
node.children = [current];
}
parentNodes.push(current)
allNodes.splice(i, 1) // 删除已经找到父节点的元素
i -= 1 // 删除元素后把索引往前挪一位
}
}
getChildrenNodes(parentNodes, allNodes, nodeUniqueIndex, nodeLinkKey)
}
export default function buildTree(data, nodeUniqueIndex = "id", nodeLinkKey = "parentId") {
const parentNodes = []; // 根节点
data.forEach((item) => {
if (!hasParentNode(data, item, nodeUniqueIndex, nodeLinkKey)) {
parentNodes.push(item);
}
});
if (parentNodes.length <= 0) return;
const dataSource = [...parentNodes];
getChildrenNodes(parentNodes, data, nodeUniqueIndex, nodeLinkKey);
return dataSource;
}