首先该扁平化数据必须是数组型的,数组各成员均为对象,每个对象都包含了id和pid两个属性,如果要将该扁平化数据转化为树形数据,则对象之间将通过id与pid关联,如果某个对象有子对象,则将其子对象放在父对象的children属性中。假设顶层对象的pid均为0,则封装的函数如下:
function flatToTree(arr) {
let res = [];
for (let i = 0; i < arr.length; i++) {
if (!arr[i].pid) {
res.push(getChildren(arr[i]));
}
}
function getChildren(parent) {
let children = [];
for (let i = 0; i < arr.length; i++) {
if (parent.id === arr[i].pid) {
children.push(getChildren(arr[i]));
}
}
if (!children.length) {
return parent;
} else {
parent.children = children;
return parent;
}
}
return res;
}