Javascript lodash _. 查找所有匹配项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35502450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lodash _.find all matches
提问by Andurit
I have simple function to return me object which meets my criteria.
我有一个简单的函数来返回符合我标准的对象。
Code looks like:
代码如下:
var res = _.find($state.get(), function(i) {
var match = i.name.match(re);
return match &&
(!i.restrict || i.restrict($rootScope.user));
});
How can I find all results (not just first) which meets this criteria but all results.
我怎样才能找到符合这个标准的所有结果(不仅仅是第一个),而是所有结果。
Thanks for any advise.
感谢您的任何建议。
回答by stasovlas
Just use _.filter
- it returns all matched items.
只需使用_.filter
- 它会返回所有匹配的项目。
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).
迭代集合的元素,返回所有元素的数组,谓词返回真值。谓词使用三个参数调用:(值、索引|键、集合)。
回答by Gerard Simpson
You can use _.filter, passing in all of your requirements like so:
您可以使用 _.filter,传入您的所有要求,如下所示:
var res = _.filter($state.get(), function(i) {
var match = i.name.match(re);
return match &&
(!i.restrict || i.restrict($rootScope.user));
});
回答by ABCD.ca
Without lodash using ES6, FYI:
没有使用 ES6 的 lodash,仅供参考:
Basic example (gets people whose age is less than 30):
基本示例(获取年龄小于 30 的人):
const peopleYoungerThan30 = personArray.filter(person => person.age < 30)
Example using your code:
使用您的代码的示例:
$state.get().filter(i => {
var match = i.name.match(re);
return match &&
(!i.restrict || i.restrict($rootScope.user));
})