Search code examples
typescriptlodash

Use multiple values in iteratee shorthad for lodash predicate


In the lodash documentation there is the following example:

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

_.filter(users, ['age', 36]);
// => objects for ['barney']

Is it possible to use a shorthand method to get the same result as the following function:

_.filter(users, ({ age }) => age === 36 || 40));
// => objects for ['barney', 'fred']

I was thinking in the line of (Code Sandbox URL with the examples):

import * as _ from "lodash";

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

// does not work
const result1 = _.filter(users, ["age", 36 || 40]);
console.info("result1: ", result1);
// => objects for ['barney']

// does not work
const result2 = _.filter(users, ["age", [36, 40]]);
console.info("result2: ", result2);
// => []


Solution

  • Short answer: no. As you can see from the documentation predicates that are not equalities are handled with functions. I think the best compromise to obtain a valid result with a similar syntax is:

    const result1 = _.filter(users, (user)=> [36,40].includes(user["age"]));
    console.info("result1: ", result1);
    

    Notice that if you are using typescript you might have to add [key: string]: any or something similar according to your object structure

    Otherwise, you have to create a function and do something like:

    const containsValueForKey = (user, key, values) => {
      return values.includes(user[key])
    }
    
    const result1 = _.filter(users, (user)=> containsValueForKey(user, "age", [36,40]));
    console.info("result1: ", result1);