// 将 input 转成output的形式
let input = [
{
id: 2,
val: '班级1',
parentId: 1,
},
{
id: 3,
val: '班级2',
parentId: 1,
},
{
id: 1,
val: '学校',
parentId: null,
},
{
id: 4,
val: '学生1',
parentId: 2,
},
{
id: 5,
val: '学生2',
parentId: 2,
},
{
id: 6,
val: '学生3',
parentId: 3,
},
];
function getTree(array) {
// 找到parentId为null的对象
let first_index = array.findIndex(item => {
if (item.parentId == null) {
return true;
}
});
// 取出对应对象并保存
let first = array[first_index];
array.splice(first_index, 1);
// 新建对象
let tree = {
id: first.id,
val: first.val,
children: array.length > 0 ? toTree(first.id, array) : [],
};
return tree;
}
function toTree(id, array) {
// 新建空数组
let l = array.length;
let children = [];
// 遍历传入的数组
for (let index = 0; index < l; index++) {
let node = array[index];
// 如果parentId等于传入的父id则添加对应对象到新建的数组中
if (node.parentId == id) {
children.push({
id: node.id,
val: node.val,
children: toTree(node.id, array),
});
}
}
return children;
}
let output = getTree(input);
console.log(output);
结果:
output = {
id: 1,
val: '学校',
children: [{
id: 2,
val: '班级1',
children: [
{
id: 4,
val: '学生1',
children: []
},
{
id: 5,
val: '学生2',
children: []
}
]
}, {
id: 3,
val: '班级2',
children: [{
id: 6,
val: '学生3',
children: []
}]
}]
}