组织树筛选符合条件数据

1,只过滤掉上层特定数据

const treeData = [{
value: '全部',
title: '全部',
hasAuthority: false,
children: [{
value: '数据库',
title: '数据库',
hasAuthority: false,
children: [{
value: 'mysql',
title: 'mysql',
hasAuthority: true,
children: [{
value: '142',
title: '慢查询',
hasAuthority: true,
}, {
value: '137',
title: 'QPS',
hasAuthority: true,
}, {
value: '143',
title: '用户列表',
hasAuthority: true,
}, ],
},
{
value: '1661',
title: 'SQL1',
hasAuthority: false,
},
{
value: '166',
title: 'SQL',
hasAuthority: true,
},
],
}],
}];

 

以上述例子看,过滤掉上层hasAuthority为false的数据,

let newChildren1 = [];
const filterSearchTree1 =(nodes)=>{
if(nodes && nodes.length>0){
for (const node of nodes) {
if(node.hasAuthority){
newChildren1.push(node)
}else{
if(node.children&&node.children.length>0){
filterSearchTree1(node.children)
}
}
}
}
return newChildren1
}

 

2 过滤掉所有特定数据

const treeData = [{
value: '全部',
title: '全部',
hasAuthority: false,
children: [{
value: '数据库',
title: '数据库',
hasAuthority: false,
children: [{
value: 'mysql',
title: 'mysql',
hasAuthority: true,
children: [{
value: '142',
title: '慢查询',
hasAuthority: true,
}, {
value: '137',
title: 'QPS',
hasAuthority: false,
}, {
value: '143',
title: '用户列表',
hasAuthority: true,
}, ],
},
{
value: '1661',
title: 'SQL1',
hasAuthority: false,
},
{
value: '166',
title: 'SQL',
hasAuthority: true,
},
],
}],
}];

let  test=filterSearchTree1(treeData)

filterSearchTree2(test)

const filterSearchTree2 =(nodes)=>{
if(nodes && nodes.length>0){
nodes.map((item,index)=>{
if(item.hasAuthority){
console.log(item)
if(item.children&&item.children.length>0){
filterSearchTree2(item.children)
}
}else{
console.log(item)
console.log(nodes)
nodes.splice(index,1)
}
})
}
}

先通过第一步筛选掉不符合的上级,然后通过第二步筛选掉不符合的下级

 

上一篇:级联选择器怎么实现选中某一级时,动态加载下一级


下一篇:并查集的创建