Dg(arr) {
// 递归函数 处理数组转化树
let dicData = toTree1(arr);
function toTree1(arr) {
const parentA = arr.filter((item) => !item.parentId);
const childA = arr.filter((item) => item.parentId);
tree1(parentA, childA);
tree2(parentA);
console.log(parentA)
return parentA;
}
function tree1(parentA, childA) {
for (const item of parentA) {
item.children = [];
for (const i in childA) {
const v = childA[i];
if (item.id === v.parentId) {
item.children.push(v);
let c = JSON.parse(JSON.stringify(childA)); // 深拷贝
c.splice(i, 1);
tree1([v], c);
}
}
}
}
function tree2(parentA) {
for (const item of parentA) {
if (item.children.length !== 0){
tree2(item.children)
}else {
delete item.children
}
}
}
},
直接使用方法,修改节点就能得到树形结构