先上最终代码:
let arr = [
{ id: 1, name: '陕西', parentId: 0 },
{ id: 2, name: '山西', parentId: 0 },
{ id: 3, name: '四川', parentId: 0 },
{ id: 4, name: '西安', parentId: 1 },
{ id: 5, name: '咸阳', parentId: 1 },
{ id: 6, name: '渭南', parentId: 1 },
{ id: 7, name: '侯马', parentId: 2 },
{ id: 8, name: '雅安', parentId: 3 },
]
let transferToTree = arr =>{
let obj = {} , tree = [];
for(let item of arr){
obj[item.id] = item;
}
for(let item of arr){
let parent = obj[item.parentId];
if(parent){
(parent.children || (parent.children = [])).push(item);
}else{
tree.push(item);
}
}
return tree;
}
console.log(transferToTree(arr))
详细解析代码:
let transferToTree = (arr) => {
let obj = {}, tree = [];
// 处理好obj
for(let item of arr){
obj[item.id] = item;
}
/*obj = {
1:{ id: 1, name: '陕西',parentId: 0},
2:{ id: 2, name: '山西',parentId: 0},
3:{ id: 3, name: '四川',parentId: 0},
4:{ id: 4, name: '西安',parentId: 1},
5:{ id: 5, name: '咸阳',parentId: 1},
6:{ id: 6, name: '渭南',parentId: 1},
7:{ id: 7, name: '侯马',parentId: 2},
8:{ id: 8, name: '雅安',parentId: 3},
}*/
for(let item of arr){
// 根据parentId和上面处理好的obj找到parent
let parent = obj[item.parentId];
/*parent =
undefined,//这是第一次的结果
undefined,//二
undefined,//三
{ id: 1, name: '陕西',parentId: 0},//四
...
*/
// 第四次的时候,走到这个分支中,给{ id: 1, name: '陕西',parentId: 0}对象添加一个属性children,值为item
if(parent){
(parent.children || (parent.children = [])).push(item)
// 没parent说明是最上层节点 直接加入tree中
}else{
tree.push(item);
}
})
return tree;
}