Filtering array of objects with lodash based on property value

sarsnake picture sarsnake · Feb 3, 2016 · Viewed 139.2k times · Source

We have an array of objects as such

var myArr = [ {name: "john", age: 23},
              {name: "john", age: 43},
              {name: "jim", age: 101},
              {name: "bob", age: 67} ];

how do I get the list of objects from myArr where name is john with lodash?

Answer

Enver Dzhaparoff picture Enver Dzhaparoff · Feb 3, 2016

Use lodash _.filter method:

_.filter(collection, [predicate=_.identity])

Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).

with predicate as custom function

 _.filter(myArr, function(o) { 
    return o.name == 'john'; 
 });

with predicate as part of filtered object (the _.matches iteratee shorthand)

_.filter(myArr, {name: 'john'});

with predicate as [key, value] array (the _.matchesProperty iteratee shorthand.)

_.filter(myArr, ['name', 'John']);

Docs reference: https://lodash.com/docs/4.17.4#filter