使用Underscorejs映射Reduce / Sum

时间:2017-03-31 21:33:20

标签: json underscore.js

我正在尝试转换以下数据集:

var data = {
"csrf": "token",

"items": [
{"category": "product1", "image": "image1.jpg", "cost": "$6", "item_totals": [
    {"category": "discount", "amount": "-$1.0"}]
},
{"category": "product2", "image": "image2.jpg", "cost": "$8", "item_totals": [
    {"category": "discount", "amount": "-$1.2"}]
}],

"totals": [
{"category": "shipping", "amount": "$0.00", "name": "Shipping", "is_zero": true},
{"category": "taxes", "amount": "$0.00", "name": "Taxes", "is_zero": true}
],
"total": "$1234", "subtotal": "$1234", "id": abc123, "currency_code": "USD"}

为单个值,是item_totals数组中所有'amount'值的总和。我似乎无法做到这一点,同时在“项目”和“项目”中记录不同数量的记录。为空'item_total'数组。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

var data = {
  "csrf": "token",

  "items": [{
      "category": "product1",
      "image": "image1.jpg",
      "cost": "$6",
      "item_totals": [{
        "category": "discount",
        "amount": "-$1.0"
      }]
    },
    {
      "category": "product2",
      "image": "image2.jpg",
      "cost": "$8",
      "item_totals": [ // multiple item_totals
        {
          "category": "discount",
          "amount": "-$1.2"
        },
        {
          "category": "discount",
          "amount": "-$1.2"
        }
      ]
    },
    {
      "category": "product2",
      "image": "image2.jpg",
      "cost": "$8",
      "item_totals": [] // empty item_totals
    },
    {
      "category": "product2",
      "image": "image2.jpg",
      "cost": "$8"
      // absent item_totals
    }

  ],

  "totals": [{
      "category": "shipping",
      "amount": "$0.00",
      "name": "Shipping",
      "is_zero": true
    },
    {
      "category": "taxes",
      "amount": "$0.00",
      "name": "Taxes",
      "is_zero": true
    }
  ],
  "total": "$1234",
  "subtotal": "$1234",
  "id": "abc123",
  "currency_code": "USD"
}


var totalAmount = _.chain(data.items)
  .map(item => item.item_totals || []) // emit totals
  .tap(console.log)
  .reduce((memo, bucket) => memo.concat(bucket), []) // collect (flatten)
  .tap(console.log)
  .map(total => parseFloat(total.amount.replace('$', ''), 10)) // emit amounts
  .tap(console.log)
  .reduce((ret, amount) => ret + amount, 0) // collect (sum)
  .value();
console.log(totalAmount);
<script src="http://underscorejs.org/underscore.js"></script>

相关问题