lodash _.find 所有匹配项

lodash _.find all matches

我有一个简单的功能return我的对象符合我的标准。

代码如下:

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

如何找到所有符合此条件的结果(不仅仅是第一个),而是所有结果。

感谢您的建议。

只需使用 _.filter - 它 returns 所有匹配项。

_.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).

您可以使用 _.filter,像这样传递您的所有要求:

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

Link to documentation

不使用 ES6 的 lodash,仅供参考:

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

const peopleYoungerThan30 = personArray.filter(person => person.age < 30)

使用您的代码的示例:

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