//数组改写成树状结构
let list =[
{id:1,name:'部门A',parentld:0},
{id:2,name:'部门B',parentld:4},
{id:3,name:'部门C',parentld:1},
{id:4,name:'部门D',parentld:0},
{id:5,name:'部门E',parentld:2},
{id:6,name:'部门F',parentld:3},
{id:7,name:'部门G',parentld:2},
{id:8,name:'部门H',parentld:4}]
<html>
<script>
    let list = [
        { id: 1, name: '部门A', parentld: 0 },
        { id: 2, name: '部门B', parentld: 4 },
        { id: 3, name: '部门C', parentld: 1 },
        { id: 4, name: '部门D', parentld: 0 },
        { id: 5, name: '部门E', parentld: 2 },
        { id: 6, name: '部门F', parentld: 3 },
        { id: 7, name: '部门G', parentld: 2 },
        { id: 8, name: '部门H', parentld: 4 }
    ]
    let listTree = []
    list.map(ele => {
        if (ele.parentld === 0) {
            listTree.push(ele)    
        }
    })
    list = list.filter(ele=>{
        return ele.parentld!==0
    })
    listTree.map(ele=>{
        changeList(ele,ele.id)
    })

    function changeList(item, id) {
     if(list.length==0)return
     item.chilren = []
     let currId= []
     list.map(ele=>{
        if(ele.parentld===id){
            item.chilren.push(ele)
            currId.push(ele.id)
        }
     })
     list = list.filter(ele=>{
        return !currId.includes(ele.id)
     })
     if(item.chilren.length>0){
        item.chilren.map(self=>{
            changeList(self,self.id)
        })
     }
    }
    console.log(listTree)
</script>

</html>

ohoherror
21 声望1 粉丝