使用.filter过滤对象数组

时间:2017-12-12 18:37:33

标签: javascript filter

如果有一个JSON对象,我如何使用.filter根据过滤器对象过滤我的数组。

data = [
   {month: 'Sep', name: 'Fred', department: 'Accounting'},
   {month: 'Sep', name: 'David', department: 'Sales'},
   {month: 'Oct', name: 'Jon', department: 'Sales'}
]

filters = {
    month: [],
    name: ['Jon'],
    department: ['Sales','Accounting']
}

4 个答案:

答案 0 :(得分:1)

 const result = data.filter(entry => {
   for(var key in filters){
     if(filters[key].length && !filters[key].includes(entry[key]) )
        return false;
   }
   return true;
});

您可以通过检查对象中存在的每个过滤器密钥以及其值包含在过滤数组中来filter 数据

答案 1 :(得分:1)

您可以使用filter()every()方法执行此操作。

var data = [
   {month: 'Sep', name: 'Fred', department: 'Accounting'},
   {month: 'Sep', name: 'David', department: 'Sales'},
   {month: 'Oct', name: 'Jon', department: 'Sales'}
]

var filters = {
    month: [],
    name: ['Jon'],
    department: ['Sales','Accounting']
}

var result = data.filter(e => {
  return Object.keys(filters).every(f => {
    return filters[f].includes(e[f]) || !filters[f].length
  })
})


console.log(result)

答案 2 :(得分:1)



let data = [
 { month: 'Sep', name: 'Fred', department: 'Accounting' },
 { month: 'Sep', name: 'David', department: 'Sales' },
 { month: 'Oct', name: 'Jon', department: 'Sales' }
];

let filters = {
  month: [],
  name: ['Jon'],
  department: ['Sales', 'Accounting']
};

let matches = data.filter(function (o) {
  // iterate through keys of filter object
  for (const key in this) {
    // if filter array is empty and
    // value is not in filter array
    if (this[key].length > 0 && !this[key].includes(o[key])) {
      // object is not match
      return false;
    }
  }
  
  // if object passed every filter array
  // object is match
  return true;
}, filters);

console.log(matches);




更简洁的写作方式可能是这样的:



let data = [
  { month: 'Sep', name: 'Fred', department: 'Accounting' },
  { month: 'Sep', name: 'David', department: 'Sales' },
  { month: 'Oct', name: 'Jon', department: 'Sales' }
];

let filters = {
  month: [],
  name: ['Jon'],
  department: ['Sales', 'Accounting']
};

let matches = data.filter(function (o) {
  return Object.keys(this).every(
    key => this[key].length === 0 || this[key].includes(o[key])
  );
}, filters);

console.log(matches);




答案 3 :(得分:0)

data.filter(obj => filters.month.indexOf(obj.month) > -1 && filters.name.indexOf(obj.name) > -1 && filters.department.indexOf(obj.department) > -1)