我有这个包含数组的列表:
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}
任何建议都非常感激。
答案 0 :(得分:0)
没有必要为此调用_.reduce
两次。 reduce
的备忘录可以是任何内容;特别是,它可以是一个对象:
summer = (memo, it) ->
memo.goodsTotal += it.price
memo.goodsVAT += it.vat
memo
totals = _(invoicedItems).reduce(
summer,
{ goodsTotal: 0, goodsVAT: 0 }
)