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?
Dustin Poissant
Lodash has a "map" function that works just like jQuerys:
var myArr = [{ name: "john", age:23 },
{ name: "john", age:43 },
{ name: "jimi", age:10 },
{ name: "bobi", age:67 }];
var johns = _.map(myArr, function(o) {
if (o.name == "john") return o;
});
// Remove undefines from the array
johns = _.without(johns, undefined)
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']);
let myArr = [
{name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67},
];
// this will return old object (myArr) with items named 'john'
let list = _.filter(myArr, item => item.name === 'jhon');
// this will return new object referenc (new Object) with items named 'john'
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
Nver Abgaryan
let myArr = [
{name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67},
];
let list = _.filter(myArr, item => item.name === "john");
来源:https://stackoverflow.com/questions/35182904/filtering-array-of-objects-with-lodash-based-on-property-value