角度-动态操纵过滤条件

时间:2019-05-27 16:36:04

标签: javascript angular

我有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中将包含HighruleFilters复选框也一样。

我想写一个函数,根据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的情况下,此功能有效。

如何涵盖以下情况的过滤条件:

  1. ruleFilters可能为空
  2. severityFilters可能为空。
  3. 已定义一个或多个严重性过滤器,但不存在ruleFilter,反之亦然。

无需编写冗长的if条件,有一种方法可以调整函数,从而无论severityFiltersruleFilters数组的长度如何,都可以对结果进行过滤。

1 个答案:

答案 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)