列表轉(zhuǎn)樹
let arr = [
{id: 1, name: '部門1', pid: 0},
{id: 2, name: '部門2', pid: 1},
{id: 22, name: '部門22', pid: 1},
{id: 222, name: '部門222', pid: 1},
{id: 3, name: '部門3', pid: 1},
{id: 4, name: '部門4', pid: 3},
{id: 5, name: '部門5', pid: 4},
]
const func = (list,pid) => list.filter(item=>item.pid == pid).map((item)=>({
...item,
children:func(list,item.id)
}))
func(arr,0)
完美一句解決,
主要原理就是通過filter篩選出當層級的數(shù)據(jù)吟温,然后通過遞歸反復(fù)調(diào)用
樹轉(zhuǎn)列表
const func1 = (treeList,accpet) => {
treeList.map(item=>func1(accpet[accpet.push(item)-1].children||[],accpet))
return accpet;
}
func1(JSON.parse(JSON.stringify(func(arr,0))),[])
這個看的有點迷糊侦啸,主要是用了js push后會返回數(shù)組長度∶担看不懂的話看下面的
const func1 = (treeList,accpet) => {
treeList.map(item=>{
accpet.push(item)
func1(item.children||[],accpet)
})
return accpet;
}
func1(JSON.parse(JSON.stringify(func(arr,0))),[])