有一组js数组:
let data=[
{id:1,parentid:0,name:'春树集团'},
{id:2,parentid:0,name:'海亮集团'},
{id:3,parentid:1,name:'科技部'},
{id:4,parentid:1,name:'设计部'},
{id:5,parentid:1,name:'运维部'},
{id:6,parentid:2,name:'科技部'},
{id:7,parentid:2,name:'客服部'},
]
使用如下代码:
let dataMap={}
data.map(item=>{
dataMap[item.id]=item
})
就得到了下面的对象:
{
'1': { id: 1, parentid: 0, name: '春树集团' },
'2': { id: 2, parentid: 0, name: '海亮集团' },
'3': { id: 3, parentid: 1, name: '科技部' },
'4': { id: 4, parentid: 1, name: '设计部' },
'5': { id: 5, parentid: 1, name: '运维部' },
'6': { id: 6, parentid: 2, name: '科技部' },
'7': { id: 7, parentid: 2, name: '客服部' }
}
然后再:
const rootList=[]
data.map(item=>{
if(!item.parentid){
rootList.push(item)
}else{
if(dataMap[item.parentid].children===undefined){
dataMap[item.parentid].children=[]
}
dataMap[item.parentid].children.push(item);
}
})
就变成了:
[
{
id: 1,
parentid: 0,
name: '春树集团',
children: [ [Object], [Object], [Object] ]
},
{
id: 2,
parentid: 0,
name: '海亮集团',
children: [ [Object], [Object] ]
}
]