使用下划线来计算带有咖啡脚本的数组元素

时间:2015-06-18 09:29:44

标签: javascript coffeescript underscore.js

我有这个包含数组的列表:

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

pricevat添加总计的正确方法是什么,以便我得到:

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

任何建议都非常感激。

1 个答案:

答案 0 :(得分:0)

没有必要为此调用_.reduce两次。 reduce的备忘录可以是任何内容;特别是,它可以是一个对象:

summer = (memo, it) ->
    memo.goodsTotal += it.price
    memo.goodsVAT   += it.vat
    memo
totals = _(invoicedItems).reduce(
    summer,
    { goodsTotal: 0, goodsVAT: 0 }
)