lodash filter on key with multiple values

戏子无情 提交于 2019-12-05 00:15:06

问题


I am trying to find out in lodash javascript library, how to find out filter array of objects multiple values of key. something similar to SQL - WHERE KEY in (val1, val2)

Having said, with following example :

var users = [
   { 'user': 'barney', 'age': 36, 'active': true },
   { 'user': 'fred',   'age': 40, 'active': false },
   { 'user': 'Avding',   'age': 34, 'active': true }
];

_.filter(...)

How can I find users, who's age in (34, 36) ?? numbers can also change runtime


回答1:


Lodash's filter accepts a predicate. You can create the predicate using partial application, so you can change the values easily:

var users = [
   { 'user': 'barney', 'age': 36, 'active': true },
   { 'user': 'fred',   'age': 40, 'active': false },
   { 'user': 'Avding',   'age': 34, 'active': true }
];

var predicate = function(start, end) {
  return function(user) {
    return _.inRange(user.age, start, end + 1);
  }
}

var result = _.filter(users, predicate(34, 36));

console.log('inRange', result);

/** is equal predicate **/

var predicate = function() {
  var args = _.toArray(arguments);
  
  return function(user) {
    var equalToUserAge = _.partial(_.isEqual, user.age);
    
    return args.some(equalToUserAge);
  }
}

var result = _.filter(users, predicate(34, 40));

console.log('equals', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

You can also do this easily with vanilla JS as well (the example uses ES6):

var users = [
   { 'user': 'barney', 'age': 36, 'active': true },
   { 'user': 'fred',   'age': 40, 'active': false },
   { 'user': 'Avding',   'age': 34, 'active': true }
];

const predicate1 = (start, end) => ({ age }) =>
  age >= start && age <= end;

const result1 = users.filter(predicate1(34, 36));

console.log('in range', result1);

const predicate2 = (...args) => ({ age }) =>
  args.some((num) => age === num);

const result2 = users.filter(predicate2(34, 40));

console.log('is equal', result2);



回答2:


const users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false },
  { 'user': 'Avding',   'age': 34, 'active': true }
];

const minAge = 34;
const maxAge = 36;

const filtered = _.filter(users, (user) => {
  return user.age >= minAge && user.age <= maxAge;
});



回答3:


You can do something like this:

_.filter( object, { 'age': '34', 'age': '24' } );

The issue is if you are making this dynamically you can not have the same key in an object more than once.



来源:https://stackoverflow.com/questions/39922160/lodash-filter-on-key-with-multiple-values