样例输入
let data = [
{ id: 0, pid: -1, name: "面试" },
{ id: 1, pid: 0, name: "计算机基础知识及原理" },
{ id: 2, pid: 0, name: "前端技能" },
{ id: 3, pid: 0, name: "综合素质" },
{ id: 4, pid: 1, name: "编码" },
{ id: 5, pid: 1, name: "操作系统" },
{ id: 6, pid: 1, name: "网络" },
{ id: 7, pid: 1, name: "数据结构" },
{ id: 8, pid: 2, name: "js" },
{ id: 9, pid: 2, name: "异步" },
{ id: 10, pid: 2, name: "项目" },
{ id: 11, pid: 3, name: "学习能力" },
{ id: 12, pid: 3, name: "解决问题能力" },
];
样例输出
{
id: 0,
pid: -1,
name: '面试',
children: [
{
id: 1,
pid: 0,
name: '计算机基础知识及原理',
children: [
{
id: 4,
pid: 1,
name: '编码'
},
{
id: 5,
pid: 1,
name: '操作系统'
},
// ...
]
},
{
id: 2,
pid: 0,
name: '前端技能',
children: [
// ...
]
},
{
id: 3,
pid: 0,
name: '综合素质',
children: [
// ...
]
}
]
}
转化方法
function buildTree(nodes) {
let tree = null; // 初始化树形结构
const record = {}; // 映射对象
const length = nodes.length;
// 初始化映射对象
for (let i = 0; i < length; i++) {
const item = nodes[i];
record[item.id] = item;
}
// 构造树形结构
for (let i = 0; i < length; i++) {
const item = nodes[i];
if (item.pid != -1) { // item不是根节点
if (record[item.pid]) {
if (!record[item.pid].children) { // item的父节点还没有children属性
record[item.pid].children = []; // 初始化父节点的children属性
}
record[item.pid].children.push(item); // 将item插入父节点的children数组
}
} else { // item是根节点
tree =item;
}
}
return tree;
}