【问题标题】:Putting values as keys from reduced object with underscore使用下划线将值作为缩减对象的键
【发布时间】:2014-04-29 23:42:22
【问题描述】:

我设法减少并将我的价格金额对象与此组合:

stooges = [{Price: 1.2, Amount: 40}, {Price: 1.3, Amount: 50}, {Price: 1.2, Amount: 60}];


inputarray = _.map  _.groupBy(stooges, 'Price'), (v, k) -> 
        {  Price: k
        Amount : _.reduce(v, ((m, i) -> m + i['Amount']), 0)}

console.log(inputarray)

创建以下内容

[Object { Price="1.2", Amount=100}, Object { Price="1.3", Amount=50}]

但也许分组太多了。无论如何,我试图以这样的方式结束

[ { 1.2 : 100 } , { 1.3 : 50 } ]

以价格为关键,以数量为价值。 该死的,我很讨厌这个。

【问题讨论】:

    标签: javascript coffeescript underscore.js


    【解决方案1】:

    试试这个:

    _.map(_.groupBy(stooges, 'Price'), function(v, k){
      var obj = {};
      obj[k] = _.reduce(v, function(m, i){ return m + i['Amount'] }, 0);
      return obj;
    })
    

    它返回以下内容:

    [{ "1.2": 100 }, { "1.3": 50 }]
    

    编辑:我不确定返回数组是否有帮助。如果您使用 Lo-Dash 而不是 Underscore(我建议您这样做),您可以使用它来代替,它将返回一个包含所有价格作为总金额键的对象:

    _(stooges).groupBy('Price').mapValues(function(stooge){
      return _(stooge).pluck('Amount').reduce(function(total, amount){
        return total + amount;
      })
    }).value()
    

    它返回以下内容:

    { "1.2": 100, "1.3": 50 }
    

    【讨论】:

      【解决方案2】:

      result1 = _.pluck inputarray,'Price'

      result2 = _.pluck inputarray,'Amount'

      boo = _.object(result1,result2);

      谢谢,现在它不像你的那么优雅!

      【讨论】:

        猜你喜欢
        • 2015-01-16
        • 2017-03-15
        • 2012-05-28
        • 2012-08-25
        • 1970-01-01
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多