使用n个过滤条件

时间:2017-11-07 05:02:18

标签: javascript arrays filter

我有一个对象数组(数据),我需要根据过滤条件(条件)过滤此数组,其中每个条件可以有多个值。

var data = [
  { ID: 1, Name: "John", Color: "Blue", Location: "Up" },
  { ID: 2, Name: "Pauline", Color: "Green", Location: "Up" },
  { ID: 3, Name: "Ahmed", Color: "Orange", Location: "Left" },
  { ID: 4, Name: "Diego", Color: "Pink", Location: "Up" },
  { ID: 5, Name: "Maria", Color: "Black", Location: "Down" },
  { ID: 6, Name: "Gus", Color: "Green", Location: "Up" },
  { ID: 7, Name: "Brian", Color: "Pink", Location: "Left" },
  { ID: 8, Name: "Shelley", Color: "Green", Location: "Right" },
  { ID: 9, Name: "Leonardo", Color: "Blue", Location: "Right" },
  { ID: 10, Name: "Big Daddy", Color: "Green", Location: "Down" }
];

var criteria = [
   { Field: "Color", Values: ["Green"] },
   { Field: "Location", Values: ["Up", "Down"] }
];

我需要一个对象数组(已过滤) 1.每个过滤标准被视为" AND" 2.过滤器字段中的多个过滤器值被视为" OR"。所以这就是输出的方式:

var filtered = [
      { ID: 2, Name: "Pauline", Color: "Green", Location: "Up" },
      { ID: 6, Name: "Gus", Color: "Green", Location: "Up" },  
      { ID: 10, Name: "Big Daddy", Color: "Green", Location: "Down" }  
    ];

2 个答案:

答案 0 :(得分:2)

您可以将Array.every用于AND条件,将array.indexOf用于OR条件。

注意,indexOf区分大小写。如果你想让它不区分大小写,你可以将两个值都转换为小写并比较

var data = [
  { ID: 1, Name: "John", Color: "Blue", Location: "Up" },
  { ID: 2, Name: "Pauline", Color: "Green", Location: "Up" },
  { ID: 3, Name: "Ahmed", Color: "Orange", Location: "Left" },
  { ID: 4, Name: "Diego", Color: "Pink", Location: "Up" },
  { ID: 5, Name: "Maria", Color: "Black", Location: "Down" },
  { ID: 6, Name: "Gus", Color: "Green", Location: "Up" },
  { ID: 7, Name: "Brian", Color: "Pink", Location: "Left" },
  { ID: 8, Name: "Shelley", Color: "Green", Location: "Right" },
  { ID: 9, Name: "Leonardo", Color: "Blue", Location: "Right" },
  { ID: 10, Name: "Big Daddy", Color: "Green", Location: "Down" },
  { ID: 11, Name: "Dummy", Color: ["Green", "Orange"], Location: "Down" }
];

var criteria = [
   { Field: "Color", Values: ["Green"] },
   { Field: "Location", Values: ["Up", "Down"] }
];

var result = data.filter(function(obj){
  return criteria.every(function(c){
    var value = obj[c.Field];
    if(typeof value === 'object') {
      return Object.keys(value).some(function(key){
        return c.Values.indexOf(value[key]) > -1
      })
    }
    else
      return c.Values.indexOf(value) > -1
  })
})
console.log(result)

答案 1 :(得分:0)

Array.some为任何匹配提供true,对每个不匹配提供false。我们期望为假,然后否定它,以便我们对原始数据的过滤条件是正确的。

filteredData = data.filter(d => 
  !(criteria.some(criterion => 
    criterion.Values.indexOf(d[criterion.Field]) === -1
   ))
)