我有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
的情况下,此功能有效。
如何涵盖以下情况的过滤条件:
无需编写冗长的if条件,有一种方法可以调整函数,从而无论severityFilters
和ruleFilters
数组的长度如何,都可以对结果进行过滤。
答案 0 :(得分:1)
您可以检查 filter 数组中的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)