请问怎么写?
发布于 4 年前 作者 XuQin15 4016 次浏览 来自 问答

1.有一个摊平的数组描叙了一系列的地理信息,类似于: var locationList=[ { id: 0, name : ”中国” } { id: 1, pid: 0 , name: ”广东省” } { id: 2 , pid:1 , name: ”深圳市” } { id: 3 , pid:2 , name: ”广州市” } … ] 其中每个节点的’pid’指向了他所属上级地区。现在要求你把这个数组输出成树状结构 var locationTree = buildLocationTree(locationList); console.log(locationTree); 其中’locationTree’的结构应该如下: interface LocationTree{ root:LocationNode; } interface LocationNode{ id: number; pid?: number: name: string; subLocations?: LocationNode[]; } 请实现’buildLocationTree()’,输出的父节点里面包含的子节点的数组

2 回复
var locationList = [
  { id: 0, name : '中国' }
 ,{ id: 1, pid:0 , name: '广东省' }
 ,{ id: 2, pid:1 , name: '深圳市' }
 ,{ id: 3, pid:2 , name: '福田区' }
 ,{ id: 4, pid:1 , name: '广州市' }
 ,{ id: 5, pid:4 , name: '黄埔区' }
];
//
function buildLocationTree(arr)
{
  let m = new Map(); // m 保存 id -> 项 的对应关系
  for(let a of arr) m.set(a.id, a);
  let r = null;
  for(let a of arr) {
    let pid = a.pid;
    if(!m.has(pid)) {
      r = a;  //找不到pid的项就是root了 
      continue;
    }
    let p = m.get(pid); //取pid对应的项
    if(!Array.isArray(p['subLocations'])) p['subLocations'] = [];
    p['subLocations'].push(a);
  }
  return {'root': r};
}
//
let t = buildLocationTree(locationList);
console.log(t);

顺便说一下,返回 {‘root’: xxx} 这种并不是很好,如果不止一个root就不好弄了。 建议返回为数组,比如这样 [{ …, sub:[] }, {…, sub:[] }]

回到顶部