1.以下为后端返回数据,需要处理为树形结构数据。
var list = [
{ id: 2, name: 'declare', parent: 0 },
{ id: 3, name: 'gps', parent: 0 },
{ id: 4, name: 'gui', parent: 1 },
{ id: 5, name: 'http', parent: 1 },
{ id: 0, name: 'api', parent: null },
{ id: 1, name: 'fetch', parent: null },
{ id: 6, name: 'lcd', parent: 1 },
{ id: 31, name: 'led', parent: 3 },
{ id: 32, name: 'mips', parent: 3 },
{ id: 33, name: 'dram', parent: 3 },
{ id: 41, name: 'dns', parent: 31 },
{ id: 42, name: 'cros', parent: 31 },
];
2.处理的过程和结果如下。
1.处理过程
function listToTree(list){
var container={};
list.forEach(item=>{
if(!container[item.parent]){
container[item.parent]=[];
}
container[item.parent].push(item);
})
return Object.values(container);
}
2.处理后的结构为