SOURCE

// 平面数组转树形
var array=[
    {id:1,parentId:null,name:'广州'},
    {id:2,parentId:1,name:'深圳'},
    {id:3,parentId:null,name:'浙江'},
    {id:4,parentId:3,name:'杭州'},
    {id:5,parentId:3,name:'金华'},
    {id:6,parentId:null,name:'北京'},
    {id:7,parentId:5,name:'东阳'},
]
/**
 * @param array
 * @param idStr 
 * @param pidStr
 */
function transformDataToTree(array,idStr,pidStr){
    let result=[];
    let map=new Map();
    if(!Array.isArray(array)){
        return result;
    }
    array.forEach((item) => {
        delete item.children;
    });
    array.forEach(item=>{
        map.set(item[idStr],item)
    })
    array.forEach(item=>{
        const parent=map.get(item[pidStr])
        if(parent){
            console.log(parent)
            if(!parent.children){
                parent.children=[];  
            }
              parent.children.push(item); 
        }else{
            result.push(item)
        }
    })
    return result;
}
// console.log(transformDataToTree(array,"id","parentId"))
//forEach
function  transToTreeForEach(array,idStr,pidStr,firstWord){
    let treeList=[];
    // treeList=array.map(item=> {
    //      if(item[pidStr]==firstWord){
    //          return item
    //      }
    // })
    array.forEach(item=> {
         if(item[pidStr]===firstWord){
             treeList.push(item);
         }
    });
    treeList.forEach(item=>
       {
            item.children=transToTreeForEach(array,"id","parentId",item["id"])
       }
    );
    return treeList;
}
// console.log(transToTreeForEach(array,"id","parentId",null))
//filter
var transToTreeFilter=function(array,idStr,pidStr,firstWord){
    let treeList=[]
    array.forEach(item=>{
        if(item[pidStr]==firstWord){
            item.children=transToTreeFilter(array,idStr,pidStr,item[idStr])
            treeList.push(item);
        }
    })
    return treeList
}
// console.log(transToTreeFilter(array,"id","parentId",null))
//forEach 和filter
// https://blog.csdn.net/WQQREN/article/details/115129940
// https://blog.csdn.net/weixin_42706743/article/details/121328290

function arrayToTree(){
    
}
console 命令行工具 X clear

                    
>
console