问题描述
我有一个添加功能,可以通过从组数组列表中搜索来添加多个组。每个组都有一个角色(或多个角色)分配给它(请参阅 listofgroupsWithRoles 数组)
- 在第一次搜索时,我将返回所有组数组(现在假设我选择了一个组作为“管理员”角色并添加它)
- 如果在第一次搜索中添加的角色是“管理员”角色,那么在下一次搜索中添加第二组时,我将不得不过滤掉所有管理员角色(因为它已经添加)并且只显示其他角色像搜索功能中的“支持”。为此,我使用过滤器方法过滤掉不是“管理员”的角色
例如: 我的数组是
func getGroupsWithRoles(){
listofgroupsWithRoles= [{
id: '1',group: 'Server group 1',role: ['Admin'],},{
id: '2',group: 'Server group 2',role: ['Admin','Support']
},{
id: 3,name: 'Server group 3',role: ['Support']
}
];
return this.listofgroupsWithRoles;
}
对于第一次搜索,我显示所有数组元素,从第二次搜索开始,我使用过滤器方法 为了过滤,我使用了两个 for 循环,因为我们有一组要比较的角色,但我变空了 数组输出。
this.filteredGroup = this.listofgroupsWithRoles().filter(x => {
for (let j=0;j<=role.length;j++){ //role is from the the fisrt search ['Admin']
for (let i=0; i<=x.role.length; i++){ //x.role is from the listofgroupsWithRoles
x.role[i] !== role[j] //checking if both are not same
}
}
});
[{
id: '1',role: ['Support']
}
];
由于已经添加了带有“Admin”的组,因此第二次搜索时。我将不得不排除或过滤掉所有没有管理员角色的组。 下面的预期输出
{
id: 3,role: ['Support']
}
--- 但我得到空白数组输出。有人能告诉我我在这里做错了什么吗?
解决方法
如果我可以提出这个建议:
基于 role = ["Admin"] 和 listOfgroupsWithRoles 是您的表。
listOfgroupsWithRoles.filter(x => {
let roleExists = false;
for (let j=0;j<role.length;j++){ //role is from the the first search ['Admin']
for (let i=0; i<x.role.length; i++){ //x.role is from the listOfgroupsWithRoles
if(x.role[i] === role[j]){ //checking if almost one value in Role table is present
roleExists = true
}
}
}
if(!roleExists) {
return true;
}
});