无需递归,空间换时间的平铺数据转树小逻辑

 
    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;
    }
posted @ 2025-04-24 11:30  孙同学你好  阅读(6)  评论(0)    收藏  举报