JavaScript:如何迭代过滤数组?

时间:2019-03-29 18:20:29

标签: javascript

我希望能够过滤一个或多个条件的数组。

请考虑以下示例数据和过滤条件:

var data = [
  {company: "Acme", fiscal_period: '01-2019', value: 10},
  {company: "Acme", fiscal_period: '02-2019', value: 15},
  {company: "Wonka", fiscal_period: '01-2019', value: 8},
  {company: "Wonka", fiscal_period: '02-2019', value: 11}
]

var filter = [{field: "company", value: "Acme"}]
console.log(myFilterFunction(data,filter));
// Desired output 
// [
//   {company: "Acme", fiscal_period: '01-2019', value: 10},
//   {company: "Acme", fiscal_period: '02-2019', value: 15}
// ]

// Now use two filters:
var filter = [{field: "company", value: "Acme"},{field: "fiscal_period", value: "01-2019"}]
console.log(myFilterFunction(data,filter);
// Desired output 
// [
//   {company: "Acme", fiscal_period: '01-2019', value: 10},
// ]

但是如何编写myFilterFunction?

我知道如何使用静态过滤器:

myFilterFunction = function(data,filter){

  return data.filter(function(el){
    return el[filter.field] === filter.value;
  });

}

console.log(myFilterFunction(data,{field: "company", value: "Acme"});

但是,如果我要使用多个过滤器,如何使其动态工作?

2 个答案:

答案 0 :(得分:2)

仅将所有返回值均为true时,将多个字段数据作为数组传递,并使用Array#every方法检查所有返回true的过滤器。

myFilterFunction = function(data,filters){    
  return data.filter(function(el){
    return filters.every(filter => el[filter.field] === filter.value);
  });    
}

console.log(myFilterFunction(data,[{field: "company", value: "Acme"},{field: "value", value: 10}]));

var data = [{
    company: "Acme",
    fiscal_period: '01-2019',
    value: 10
  },
  {
    company: "Acme",
    fiscal_period: '02-2019',
    value: 15
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 8
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 11
  }
]

myFilterFunction = function(data, filters) {
  return data.filter(function(el) {
    return filters.every(filter => el[filter.field] === filter.value);
  });
}

console.log(myFilterFunction(data, [{
  field: "company",
  value: "Acme"
}, {
  field: "value",
  value: 10
}]));

使用ES6 Destructuring parameterarrow function

myFilterFunction = (data,filters) => {    
  return data.filter(el => filters.every(({ field, value }) => el[field] === value));    
}

var data = [{
    company: "Acme",
    fiscal_period: '01-2019',
    value: 10
  },
  {
    company: "Acme",
    fiscal_period: '02-2019',
    value: 15
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 8
  },
  {
    company: "Wonka",
    fiscal_period: '01-2019',
    value: 11
  }
]


    myFilterFunction = (data,filters) => {    
      return data.filter(el => filters.every(({ field, value }) => el[field] === value));    
    }

console.log(myFilterFunction(data, [{
  field: "company",
  value: "Acme"
}, {
  field: "value",
  value: 10
}]));

答案 1 :(得分:0)

data.filter(el=>{
    for(let t in filterArray){
        if(el[t]!=filterArray[t]){
            return false;
        }
    }
    return true;
})

像这样