数据
let data = [
{id: 1, title: 'hello', parent: 0},
{id: 3, title: 'hello', parent: 1},
{id: 4, title: 'hello', parent: 3},
{id: 5, title: 'hello', parent: 4},
{id: 2, title: 'hello', parent: 0},
{id: 6, title: 'hello', parent: 4},
{id: 7, title: 'hello', parent: 3},
{id: 8, title: 'hello', parent: 10}
]
arr ----- tree
function tree(data){
// let newArr=JSON.parse(JSON.stringify(data))
data.forEach(item=>{
if(item.parent!==0){
data.forEach(val=>{
if(val.id==item.parent){ //如果内循环的id==外循环的parent 内与外即为父子关系
if(!val.children){
val.children=[]
}
val.children.push(item) //向父节点的children中添加item.parent == val.id的元素
}
})
}
})
data=data.filter(item=>item.parent===0) //去重 只有parent==0的时候才是最高级父节点
return data
}
tree ----- arr
以上面转换出的tree为例
let treeList=tree(data)
let newArr=[]
function arr(treeList){
treeList.forEach(item=>{
newArr.push(item)
item.children && item.children.length > 0 ? arr(item.children) : ""
})
return newArr
}