//嵌套目录层级
//将具有父id的对象数组转换为对象嵌套结构
//参考:https://stackoverflow.com/questions/18017869/build-tree-array-from-flat-array-in-javascript
//list为待转换的对象数组,key为表示父id的键名
function doListToTree(list,key='father_id') {
let map = {}, outData = [];
list.map((item,index)=>{
map[list[index].id] = index; // 初始化map
list[index].children = []; // 初始化children
})
list.map((item)=>{
if (item[key] !== 0) {
// 检查 map[item[key]] 是否存在,以判断悬垂的分支(父id不存在的分支)
// 出现此问题一般是由于父id已删除,但是没有删除掉其子id
if(map[item[key]]===undefined){
console.log('悬垂的分支 -> ',item);
//TODO: 向错误监控平台报告错误
}else{
list[map[item[key]]].children.push(item);
}
} else {
outData.push(item);
}
})
return outData;
}
输入:
let menu = [
{"id":12,"parentId":0},
{"id":6,"parentId":12},
{"id":7,"parentId":12},
{"id":8,"parentId":7},
{"id":18,"parentId":8},
{"id":28,"parentId":18},
{"id":9,"parentId":0},
{"id":11,"parentId":9},
{"id":15,"parentId":88}
];
console.log(doListToTree(menu,'parentId'));
输出:
[{
"id": 12,
"parentId": 0,
"children": [{
"id": 6,
"parentId": 12,
"children": []
}, {
"id": 7,
"parentId": 12,
"children": [{
"id": 8,
"parentId": 7,
"children": [{
"id": 18,
"parentId": 8,
"children": [{
"id": 28,
"parentId": 18,
"children": []
}]
}]
}]
}]
}, {
"id": 9,
"parentId": 0,
"children": [{
"id": 11,
"parentId": 9,
"children": []
}]
}]