function toTree(arr){
let copyArr = JSON.parse(JSON.stringify(arr)) //深拷贝源数据
return copyArr.filter(parent=>{
let children = copyArr.filter(child=> child.parentId===parent.id)
parent.children = children.length>0 ? children : []
return parent.parentId == null //返回顶层,依据实际情况判断这里的返回值
})
}
console.log(toTree(arr))
let arr= [
{ id:0, parentId:null, name:"顶级菜单" },
{ id:1, parentId:0, name:"一级菜单A" },
{ id:2, parentId:0, name:"一级菜单B"},
{ id:3, parentId:0, name:"一级菜单C"},
{ id:4, parentId:1, name:"二级菜单A-A"},
{ id:5, parentId:1, name:"二级菜单A-B"},
{ id:6, parentId:2, name:"二级菜单B-A"},
{ id:7, parentId:4, name:"三级菜单A-A-A"},
{ id:8, parentId:7, name:"四级菜单A-A-A-A"},
{ id:9, parentId:8, name:"五级菜单A-A-A-A-A"},
];
网友评论