列表转树
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筛选出当层级的数据,然后通过递归反复调用
树转列表
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后会返回数组长度。看不懂的话看下面的
const func1 = (treeList,accpet) => {
treeList.map(item=>{
accpet.push(item)
func1(item.children||[],accpet)
})
return accpet;
}
func1(JSON.parse(JSON.stringify(func(arr,0))),[])