lodash _.find所有比赛

And*_*rit 44 javascript lodash

我有简单的功能来返回符合我标准的对象.

代码如下:

    var res = _.find($state.get(), function(i) {
        var match = i.name.match(re);
        return match &&
            (!i.restrict || i.restrict($rootScope.user));
    });
Run Code Online (Sandbox Code Playgroud)

我怎样才能找到符合此标准但所有结果的所有结果(不仅仅是第一个).

谢谢你的建议.

sta*_*las 92

只需使用_.filter- 它返回所有匹配的项目.

_.过滤

迭代集合的元素,返回所有元素的数组谓词返回truthy.使用三个参数调用谓词:(value,index | key,collection).


Ger*_*son 7

您可以使用_.filter,传递所有要求,如下所示:

var res = _.filter($state.get(), function(i) {
        var match = i.name.match(re);
        return match &&
            (!i.restrict || i.restrict($rootScope.user));
    });
Run Code Online (Sandbox Code Playgroud)

链接到文档


ABC*_*.ca 5

在不使用ES6和lodash的情况下,仅供参考:

基本示例(获取年龄小于30岁的人):

const peopleYoungerThan30 = personArray.filter(person => person.age < 30)
Run Code Online (Sandbox Code Playgroud)

使用代码的示例:

$state.get().filter(i => {
    var match = i.name.match(re);
    return match &&
            (!i.restrict || i.restrict($rootScope.user));
})
Run Code Online (Sandbox Code Playgroud)