Javascript 将值作为带下划线的简化对象的键
我设法将我的Price Amount对象与以下内容结合起来:Javascript 将值作为带下划线的简化对象的键,javascript,coffeescript,underscore.js,Javascript,Coffeescript,Underscore.js,我设法将我的Price Amount对象与以下内容结合起来: 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
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 }]
{ "1.2": 100, "1.3": 50 }
编辑:我不确定返回数组是否有帮助。如果您使用的是Lo Dash而不是下划线(我建议您这样做),您可以使用它,它将返回一个包含所有价格的单个对象作为总金额的键:
_(stooges).groupBy('Price').mapValues(function(stooge){
return _(stooge).pluck('Amount').reduce(function(total, amount){
return total + amount;
})
}).value()
它返回以下内容:
[{ "1.2": 100 }, { "1.3": 50 }]
{ "1.2": 100, "1.3": 50 }
结果1=u.pull输入数组,'Price' 结果2=u.purch输入数组,'Amount' boo=\对象(result1,result2) 谢谢,现在拿到了,没有你的那么优雅