Filtering array of objects with lodash based on property value

喜你入骨 提交于 2019-11-27 01:32:44

问题


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?


回答1:


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)



回答2:


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



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!