js
复制代码
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
// 定义tree node 并加入map
const treeNode = { id, name }
idToTreeNode.set(id, treeNode)
// 找到parentNode 并加入到它的children
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)