我们有一个这样的对象数组
var myArr = [ {name: "john", age: 23},
{name: "john", age: 43},
{name: "jim", age: 101},
{name: "bob", age: 67} ];
如何从 myArr 中获取名称为 john 和 lodash 的对象列表?
最佳答案
使用 lodash _.filter
方法:
_.filter(collection, [predicate=_.identity])
遍历集合的元素,返回所有元素的数组 predicate returns truthy for。使用三个参数调用谓词: (值、索引|键、集合)。
将谓词作为自定义函数
_.filter(myArr, function(o) {
return o.name == 'john';
});
将谓词作为过滤对象的一部分(_.matches
iteratee 速记)
_.filter(myArr, {name: 'john'});
将谓词作为 [key, value] 数组(_.matchesProperty
iteratee 简写。)
_.filter(myArr, ['name', 'John']);
关于javascript - 根据属性值使用 lodash 过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35182904/