Lodash按对象过滤

时间:2016-09-15 07:04:18

标签: javascript lodash

你知道如何在lodash中编写一个函数来过滤一个具有过滤器的对象数组吗?

const arr = [{a: 1, b:22, c:44, }, {a: 123, b: 33, c: 3}, {d: 'example'}];

//Behavior

filters = { d: 'e' };
//result [{d: 'example']

filters = { b: 3, a: 1}
//result [{a: 123, b: 33, c: 3}]

filters = { b: 2, d: 'e' };
//result []

我的解决方案:

filterRows (originalRows, filters) {
  filters = _.toPairs(filters);
  return originalRows.filter(row =>
    filters.every(([filterKey, filterValue]) => {
      const rowValue = _.toLower(row[filterKey]), 
            filter = _.toLower(filterValue);
      return rowValue.includes(filter); 
    })
  );
}

但也许可以用更干净的方式来写这个。

2 个答案:

答案 0 :(得分:1)

我想一个简单的纯JS函数就足够了;

var arr = [{a: 1, b:22, c:44, }, {a: 123, b: 33, c: 3}, {d: 'example'}],
filter1 = { d: 'e' },
filter2 = { b: 3, a: 1},
filter3 = { b: 2, d: 'e' },
 filter = (a,f) => a.filter(o => { var oks = Object.keys(f);
 	                               return oks.every(k => o[k] !== void 0 && (o[k]+"").indexOf(f[k]) !== -1);
                                 });
console.log(filter(arr,filter1));
console.log(filter(arr,filter2));
console.log(filter(arr,filter3));

答案 1 :(得分:-1)

non-lodash解决方案:

考虑传递对象,使用广义函数来过滤数组,

const arr = [{
  a: 1,
  b: 22,
  c: 44,
}, {
  a: 123,
  b: 33,
  c: 3
}, {
  d: 'example'
}];
var filters1 = {
  d: 'e'
};
var filters2 = {
  b: 3,
  a: 1
};
var filters3 = {
  b: 2,
  d: 'e'
};

function filterObject(array, filter) {
  var keys = Object.keys(filter);
  return array.filter(function(el) {
    return keys.every(function(k) {
      return el[k] && el[k].toString().indexOf(filter[k].toString()) !== -1;
    });
  });
}
console.log(filterObject(arr, filters1));
console.log(filterObject(arr, filters2));
console.log(filterObject(arr, filters3));

Fiddle Demo