【问题标题】:lodash _.find all matcheslodash _.查找所有匹配项
【发布时间】:2016-05-31 20:35:03
【问题描述】:

我有一个简单的函数可以返回符合我条件的对象。

代码如下:

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

我怎样才能找到符合此条件的所有结果(不仅仅是第一个),而是所有结果。

感谢您的建议。

【问题讨论】:

  • 您在寻找_.filter吗?

标签: javascript lodash


【解决方案1】:

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

_.filter

遍历集合的元素,返回所有元素的数组,谓词返回truthy for。谓词使用三个参数调用:(值、索引|键、集合)。

【讨论】:

    【解决方案2】:

    没有 lodash 使用 ES6,仅供参考:

    基本示例(获取年龄小于 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));
    })
    

    【讨论】:

      【解决方案3】:

      您可以使用 _.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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多