将城市数组转化成树形结构
使用循环方法,非递归
var list = [
{
id: 1,
city:'广东',
pid: null
},
{
id: 2,
city:'中山',
pid: 1
},
{
id: 3,
city:'石歧',
pid: 2
},
{
id: 4,
city:'广州',
pid: 1
}
]
function buildTree(list){
let temp = {};
let tree = {};
for(let i of list){
temp[i.id] = i;
}
for(let i in temp){
if(temp[i].pid) {
if(!temp[temp[i].pid].children) {
temp[temp[i].pid].children = {};
}
temp[temp[i].pid].children[temp[i].id] = temp[i];
} else {
tree[temp[i].id] = temp[i];
}
}
return tree;
}
console.log(buildTree(list))