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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With