Skip to main content

树形结构

creatTree(list: Array<any>) {
const tree = [];
const mapObj = {};
list.forEach(item => {
mapObj[item.code] = item;
item.isLeaf = true;
item.children = [];
});
list.forEach(item => {
const parent = mapObj[item.parentCode];
if (parent) {
parent.isLeaf = false;
parent.children.push(item);
} else {
item.isLeaf = item.children.length === 0;
tree.push(item);
}
});
console.log('处理后的树', tree);
return tree;
}
createTree(treeData: Array<any>, pid: string) {
const treeArr = [];
treeData.forEach((item, index) => {
const treeNode = {
...item,
childs: [],
};
if (item.parentMenuId === pid) {
const childs = this.createTree(treeData, item.id);
if (childs && childs.length > 0) {
treeNode.childs = childs;
}
treeArr.push(treeNode);
}
});
console.log('处理后的树', tree);
return treeArr;
}