我有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复选框相同。

我想写一个函数,根据severityFiltersruleFilters中的值返回一些过滤后的结果。选中每个过滤器复选框后,将调用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]];
              }
            }
    }
    }


考虑到同时指定了severityFiltersruleFilters的情况,此函数有效。

如何涵盖以下情况的过滤检查:


ruleFilters可能为空
alityFilters可能为空。
定义了一个或多个严重性过滤器,但不存在ruleFilters,反之亦然。


如果不写冗长的if条件,则有一种方法可以调整函数,以使结果被过滤,无论severityFiltersruleFilters数组的长度如何。

最佳答案

您可以在检查过滤器数组是否包含属性值之前检查它们是否包含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)

09-26 10:05