function arrayToTreeIterative(items) {
const map = new Map();
const tree = []
//创建节点映射
items.forEach(item=>{
map.set(item.id,{...item,children:[]})
})
//创建树结构
items.forEach(item=>{
const node=map.get(item.id)
if(item.parentId===null||item.parentId===undefined){
tree.push(node)
}else {
const parent = map.get(item.parentId)
if(parent){
parent.children.push(node)
}
}
})
return tree
}
const flatArray = [
{ id: 1, name: "部门A", parentId: null },
{ 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 }
];
console.log(arrayToTreeIterative(flatArray))
console