sarsnake sarsnake - 12 days ago 5
Javascript Question

Filtering array of objects with lodash based on property value

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

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']);
Comments