使用下划线对带有咖啡脚本的数组元素进行总计
using underscore to total array elements with coffee script
我有这个包含数组的列表:
invoicedItems = [
{ sku: 'EP01-MGY1'
quantity: 10
unit_price: 473
vat: 0
price: 4730 },
{ sku: 'EP01-MGY2'
quantity: 80
unit_price: 426
vat: 0
price: 34080 },
{ sku: 'EP01-MGY3'
quantity: 1
unit_price: 612
vat: 0
price: 612 },
]
添加 price
和 vat
总数的正确方法是什么,这样我得到:
{ goodsTotal: XXX, goodsVAT: YYY }
我试过这个:
if invoicedItems
console.log invoicedItems
result.invoicedGoodsTotals =
goodsTotal: _.reduce( invoicedItems.items, ((s,it) -> s + it.price), 0 )
goodsVAT: _.reduce( invoicedItems.items, ((s,it) -> s + it.vat), 0 )
console.log result.invoicedGoodsTotals
但这没有用。
只返回
{ goodsTotal: 0, goodsVAT: 0 }
非常感谢任何建议。
不需要为此调用 _.reduce
两次。 reduce
的备忘录可以是任何内容;特别是,它可以是一个对象:
summer = (memo, it) ->
memo.goodsTotal += it.price
memo.goodsVAT += it.vat
memo
totals = _(invoicedItems).reduce(
summer,
{ goodsTotal: 0, goodsVAT: 0 }
)
我有这个包含数组的列表:
invoicedItems = [
{ sku: 'EP01-MGY1'
quantity: 10
unit_price: 473
vat: 0
price: 4730 },
{ sku: 'EP01-MGY2'
quantity: 80
unit_price: 426
vat: 0
price: 34080 },
{ sku: 'EP01-MGY3'
quantity: 1
unit_price: 612
vat: 0
price: 612 },
]
添加 price
和 vat
总数的正确方法是什么,这样我得到:
{ goodsTotal: XXX, goodsVAT: YYY }
我试过这个:
if invoicedItems
console.log invoicedItems
result.invoicedGoodsTotals =
goodsTotal: _.reduce( invoicedItems.items, ((s,it) -> s + it.price), 0 )
goodsVAT: _.reduce( invoicedItems.items, ((s,it) -> s + it.vat), 0 )
console.log result.invoicedGoodsTotals
但这没有用。
只返回
{ goodsTotal: 0, goodsVAT: 0 }
非常感谢任何建议。
不需要为此调用 _.reduce
两次。 reduce
的备忘录可以是任何内容;特别是,它可以是一个对象:
summer = (memo, it) ->
memo.goodsTotal += it.price
memo.goodsVAT += it.vat
memo
totals = _(invoicedItems).reduce(
summer,
{ goodsTotal: 0, goodsVAT: 0 }
)