let arr = [
{ id: 8, name: '部门1', pid: 10 },
{ id: 1, name: '部门1', pid: 0 },
{ id: 2, name: '部门2', pid: 1 },
{ id: 3, name: '部门3', pid: 1 },
{ id: 4, name: '部门4', pid: 3 },
{ id: 5, name: '部门5', pid: 4 },
{ id: 6, name: '部门5', pid: 4 },
]
function arrToTree(arr) {
const map = {}
const arrWithMap = arr.map(item => {
let res = { ...item }
res.children = []
map[res.id] = res
return res
})
const tree = []
arrWithMap.forEach(item => {
const parent = map[item.pid]
if (!parent) {
tree.push(item)
return
}
parent.children.push(item)
})
return tree
}
let tree = arrToTree(arr)
console.log(tree)
console