一天一道面试题!数组转树结构~

97 阅读1分钟
``` const arr = [{
        id: 2,
        name: '部门B',
        parentId: 0
    },
    {
        id: 20,
        name: '部门cccC',
        parentId: 0
    },
    {
        id: 3,
        name: '部门C',
        parentId: 1
    },
    {
        id: 1,
        name: '部门A',
        parentId: 2
    },
    {
        id: 4,
        name: '部门D',
        parentId: 1
    },
    {
        id: 5,
        name: '部门E',
        parentId: 2
    },
    {
        id: 6,
        name: '部门F',
        parentId: 4
    },
    {
        id: 7,
        name: '部门G',
        parentId: 2
    },
    {
        id: 8,
        name: '部门H',
        parentId: 4
    }
]

function fn(obj,n){
    let result = [];
    loop(obj,n)
    function loop(obj,n){
        let tmp = {
            num:n,
            list:[]
        };
        let ccc= [];
        for(let i=obj.length; i--; i>0){
            obj[i]['children'] = [];
            if(obj[i].parentId == n){
                tmp.list.push(obj[i])
                tmp.num = obj[i].parentId;
            }else{
                ccc.push(obj[i])
            }
        }
        if(tmp.list.length>0){
            result.push(tmp);
        }

        n++;
        if(ccc.length>0){
            loop(ccc,n)
        }
    }
    for(let i=result.length-1; i--; i>0){
        result[i].list.filter(item=>{
            item.children.push(result[i+1].list)
        })
    }
    return result[0].list;
}
console.log(fn(arr,0))