【问题标题】:using underscore to total array elements with coffee script使用下划线对带有咖啡脚本的数组元素进行总和
【发布时间】:2015-06-18 23:58:08
【问题描述】:

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

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

但这不起作用。

只返回

{ 商品总数:0,商品增值税:0 }

非常感谢任何建议。

【问题讨论】:

  • invoicedItems.items 更改为 invoicedItems,它应该可以工作。
  • 谢谢,太好了

标签: javascript coffeescript underscore.js


【解决方案1】:

无需为此致电_.reduce 两次。 reduce 的备忘录可以是任何东西;特别是,它可以是一个对象:

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

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 2015-02-25
    • 2012-04-05
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    相关资源
    最近更新 更多