无需递归,空间换时间的平铺数据转树小逻辑
let listToTree = function(list,rootId=0){
const map = new Map();
const tree =[];
for(const item of list){
map.set(item.id,{...item,children:[]});
}
for(const item of list){
const node = map.get(item.id);
if(item.parentId === rootId){
tree.push(node);
}else {
const parent = map.get(item.parentId);
if(parent){
parent.children.push(node);
}
}
}
return tree;
}

浙公网安备 33010602011771号