思路:
1、遍历数组结构
2、给每个元素,生成 tree node
3、找到parentNode, 并加入它的children
const arr = [
{ id: 1, name: "部门A", parentId: 0 },
{ id: 2, name: "部门B", parentId: 1 },
{ id: 3, name: "部门C", parentId: 1 },
{ id: 4, name: "部门D", parentId: 2 },
{ id: 5, name: "部门E", parentId: 2 },
{ id: 6, name: "部门F", parentId: 3 },
]
function toTree(arr) {
const idToTreeNode = new Map()
let root = null
arr.forEach(item => {
const { id, name, parentId } = item
const treeNode = { id, name }
idToTreeNode.set(id, treeNode)
const parentNode = idToTreeNode.get(parentId)
if (parentNode) {
if (parentNode.children == null) parentNode.children = []
parentNode.children.push(treeNode)
}
if (parentId === 0) root = treeNode
})
return root
}
const show = toTree(arr)
console.log('show', show)