const filterReceiveDeptTree = computed(() => {
if (state.filterText) {
let deepclone = deepClone(state.receiveDeptTree);
const filteredTree = filterTree(
deepclone,
(node) => {
return node.name.includes(state.filterText);
},
state.switchKeepPers
);
console.log(filteredTree);
return filteredTree;
} else {
return state.receiveDeptTree;
}
});
/**
* 过滤树,返回符合条件的节点以及它的上级节点,以及是否保留它的下级节点
* @param {*} node 树节点
* @param {*} conditions 过滤条件
* @param {*} keepChildren 是否保留子节点
*/
const filterTree = (node, conditions, keepChildren = true) => {
return node.filter((item) => {
// 节点本身符合条件
if (conditions(item)) {
// 如果有子节点,返回符合条件的子节点
if (item.children && item.children.length && keepChildren == false) {
item.children = filterTree(item.children, conditions, keepChildren);
}
// 保留人员节点
else if (item.children && item.children.length && keepChildren == true) {
let dept = item.children.filter((s) => s.type == 'JG');
let pers = item.children.filter((s) => s.type == 'RY');
let arr = [];
if (dept.length) {
let res = filterTree(dept, conditions, keepChildren);
arr = arr.concat(res);
}
if (pers.length) {
arr = arr.concat(pers);
}
if (arr.length) {
item.children = arr;
return true;
}
}
return true;
}
// 节点本身不符合条件,但是子节点有符合条件的
else if (item.children && item.children.length) {
// 递归过滤子节点,返回符合条件的子节点
const res = filterTree(item.children, conditions, keepChildren);
if (res.length) {
item.children = res;
return true;
}
}
return false;
});
};
标签:arr,return,children,item,过滤,keepChildren,下级,节点
From: https://www.cnblogs.com/lbx6935/p/17700373.html