-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2609b51
commit fa6ce8a
Showing
2 changed files
with
92 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,42 @@ | ||
# 平铺的节点转树 | ||
# 平铺的节点转树 | ||
|
||
```js | ||
function listToTree(nodes) { | ||
const rootNodes = []; | ||
const nodeMap = {}; | ||
|
||
// 将节点存储在哈希表中 | ||
for (let node of nodes) { | ||
nodeMap[node.id] = { ...node, children: [] }; | ||
} | ||
|
||
// 构建树结构 | ||
for (let node of nodes) { | ||
// 判断当前节点是否有父节点 | ||
const parentNode = nodeMap[node.parentId]; | ||
// 如果有父节点,直接为该父节点children添加当前节点 | ||
if (parentNode) { | ||
parentNode.children.push(nodeMap[node.id]); | ||
} else { | ||
// 没有父节点,直接push | ||
rootNodes.push(nodeMap[node.id]); | ||
} | ||
} | ||
|
||
return rootNodes; | ||
} | ||
|
||
// 平铺的节点数组示例 | ||
const nodes = [ | ||
{ id: 1, name: 'Node 1', parentId: null }, | ||
{ id: 2, name: 'Node 1.1', parentId: 1 }, | ||
{ id: 3, name: 'Node 1.1.1', parentId: 2 }, | ||
{ id: 4, name: 'Node 1.2', parentId: 1 }, | ||
{ id: 5, name: 'Node 2', parentId: null }, | ||
{ id: 6, name: 'Node 2.1', parentId: 5 } | ||
]; | ||
|
||
// 转换为树状结构 | ||
const tree = listToTree(nodes); | ||
console.log(tree); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters