Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 310
sarsnake Avatar asked Feb 03 '16 16:02

sarsnake


People also ask

How do you filter an array of objects by value?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you sort an array of objects in Lodash?

The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements.


1 Answers

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

like image 155
Enver Dzhaparoff Avatar answered Oct 20 '22 12:10

Enver Dzhaparoff