【问题标题】:Combining Lodash Methods结合 Lodash 方法
【发布时间】:2017-07-14 14:38:38
【问题描述】:

是否可以将 ._max 和 pluck 结合起来?

Finding Max Works 并返回 scoreLabel 最高的对象

var maxScore = _.max(peopleList, scoreLabel);

但是将它与 pluck 结合会返回一个未定义的列表

_.pluck(_.max(peopleList, scoreLabel), scoreLabel);

【问题讨论】:

    标签: javascript filter lodash


    【解决方案1】:

    _.max(peopleList, scoreLabel) 返回一个人,而不是一个人的集合,因此您可以使用括号表示法简单地访问其scoreLabel 属性以获取maxScore

    var maxScore = _.max(peopleList, scoreLabel)[scoreLabel]
    

    最新版本的 Lodash 看起来像 _.pluck has also been deprecated in favor of _.map(list, 'property')

    【讨论】:

      【解决方案2】:

      _.pluck 的目的是为集合中的每个对象检索一个字段 - 因为_.max 只返回一个对象,所以你不需要采摘,你可以简单地检索您拥有的一个对象的字段:

      var maxScore = _.max(peopleList, scoreLabel)[scoreLabel];
      

      上面将从peopleList中检索scoreLabel最大的人,然后检索该人的scoreLabel值。

      或者,您可以将调用的顺序交换为_.max_.pluck,如下所示:

      var maxScore = _.max(_.pluck(peopleList, scoreLabel));
      

      这将构建所有 scoreLabel 值的集合,然后检索最大的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多