//示例数组
let list = [
{ id: 1, perId: 0, leve: 1 },
{ id: 2, perId: 0, leve: 1 },
{ id: 3, perId: 0, leve: 1 },
{ id: 11, perId: 1, leve: 2 },
{ id: 12, perId: 1, leve: 2 },
{ id: 13, perId: 1, leve: 2 },
{ id: 21, perId: 11, leve: 3 },
{ id: 31, perId: 21, leve: 4 },
{ id: 66, perId: 2, leve: 2 },
{ id: 104, perId: 66, leve: 3 },
{ id: 203, perId: 104, leve: 4 },
{ id: 499, perId: 203, leve: 5 }
]
function tree(list) {
let map = {};
list.map(e=>map[e.id] = e);
list.map(e=>{
if(map[e.perId]){
map[e.perId].child ? map[e.perId].child.push(e) : map[e.perId].child = [e]
}
})
let newList = Object.keys(map).map(e=>map[e])
return newList.filter(e=>e.perId === 0)
}
console.log(tree(list));
代码如上 只需要数据渲染逻辑如上,一维数组的每个数据都具有元素id和父id即可做到转换自如(代码中元素id为id,父id为perId)