作者: 文章来源:
本文原地址:https://www.mimiwuqi.com/webqianduan/195952.html
目录文章目录最近项目用 el-tree 做一个组织结构树展示,产品要求只展示 5 层层级关系即可,这里不包括祖辈这一层。

这里一共总结了 3 种实现方式。
getOrgnizes().then((res) => {
let arr = [];
res.forEach((i) => {
if (i.child && i.child.length) {
i.child.forEach((j) => {
if (j.child && j.child.length) {
j.child.forEach((k) => {
if (k.child && k.child.length) {
k.child.forEach((l) => {
if (l.child && l.child.length) {
l.child.forEach((m) => {
if (m.child && m.child.length) {
m.child.forEach((n) => {
if (n.child && n.child.length) {
// n.disabled = true;
delete n.child;
}
});
}
});
}
});
}
});
}
});
}
arr.push(i);
});
this.treeData = arr;
});
但是这样虽然能实现效果,但是有点啰嗦,不灵活。
const limitLevel = (tree, level) => {
if (!tree) return
for (const node of tree) {
if (level == 1) delete node.child
else limitLevel(node.child, level - 1)
}
}
// 利用可选链简写版
// const limitLevel = (tree, level) => tree?.forEach(node => {
// if (level == 1) delete node.child
// else limitLevel(node.child, level - 1)
// })
limitLevel(res, 5)
this.treeData = res
const limitLevel = (tree, level) => {
while (--level) tree = tree.flatMap(node => node.child || [])
tree.forEach(node => delete node.child)
}
limitLevel(res, 5)
this.treeData = res
更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/