我有3个数组。
var severityFilters = ["High", "Medium", "Low"]
var ruleFilters = ["true", "false"]
var allResults = [
{
"name": "Test1",
"severity": "High",
"clean": true
},
{
"name": "Test2",
"severity": "Low",
"clean": false
},
{
"name": "Test3",
"severity": "Medium",
"clean": false
},
{
"name": "Test4",
"severity": "High",
"clean": true
}
]
当用户选中和取消选中某些过滤器复选框时,动态创建
severityFilters
数组和ruleFilters
。因此,如果未选中severityFilters
复选框,则该数组为空。如果仅选中High
,则severityFilters
中将包含High
。与ruleFilters
复选框相同。我想写一个函数,根据
severityFilters
和ruleFilters
中的值返回一些过滤后的结果。选中每个过滤器复选框后,将调用filterResults
函数。var filteredResults = []
filterResults (severityFilters, ruleFilters, allResults)
{
for (let i = 0; i < allResults.length; i++) {
if (severityFilters.length > 0 && ruleFilters.length > 0)
{
if (ruleFilters.includes(this.allResults[i].clean.toString()) &&
severityFilters.includes(allResults[i].severity)
)
{
this.filteredResults = [...this.filteredResults, ...allResults[i]];
}
}
}
}
考虑到同时指定了
severityFilters
和ruleFilters
的情况,此函数有效。如何涵盖以下情况的过滤检查:
ruleFilters可能为空
alityFilters可能为空。
定义了一个或多个严重性过滤器,但不存在ruleFilters,反之亦然。
如果不写冗长的if条件,则有一种方法可以调整函数,以使结果被过滤,无论
severityFilters
和ruleFilters
数组的长度如何。 最佳答案
您可以在检查过滤器数组是否包含属性值之前检查它们是否包含length
。如果severityFilters
为空,则!severityFilters.length
将返回true。因此,由于includes
,它不会检查第二个||
条件。如果severityFilters
确实有某个值,则将检查severityFilters.includes(o.severity)
,并且仅过滤severity
中具有severityFilters
值的那些对象
const severityFilters = ["High"]
const ruleFilters = ["true", "false"]
var allResults=[{name:"Test1",severity:"High",clean:true},{name:"Test2",severity:"Low",clean:false},{name:"Test3",severity:"Medium",clean:false},{name:"Test4",severity:"High",clean:true}];
const output = allResults.filter(o =>
(!severityFilters.length || severityFilters.includes(o.severity)) &&
(!ruleFilters.length || ruleFilters.includes(o.clean.toString()))
)
console.log(output)