繁体   English   中英

将值作为下划线对象的键并带有下划线

[英]Putting values as keys from reduced object with underscore

我设法减少并结合了我的价格对象:

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 } ]

以价格为关键,金额为价值。 我该死的

尝试这个:

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

result1 = _.pluck输入数组,'价格'

result2 = _.pluck inputarray,'Amount'

boo = _.object(result1,result2);

谢谢,现在它还没有您的优雅!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM