reduce()函数计算产品总数

时间:2018-06-06 20:36:03

标签: javascript json vue.js vuejs2 reduce

{
  "orders" : [ null, {
    "comment" : "Bitte, Lassen Sie die Pizza geschnitten.",
    "date" : "2018-06-01 07:22:10",
    "item" : [ {
      "name" : "Tomatensuppe",
      "price" : 3.9,
      "quantity" : 2,
      "size" : ""
    }, {
      "name" : "Estragoncremesuppe",
      "price" : 4.5,
      "quantity" : 1,
      "size" : ""
    } ]
  }, {
    "comment" : "Geben Sie Brot dazu",
    "date" : "2018-03-19 15:22:20",
    "item" : [ {
      "name" : "Minestrone",
      "price" : 3.9,
      "quantity" : 3,
      "size" : ""
    }, {
      "name" : "Tomatensuppe",
      "price" : 3.9,
      "quantity" : 2,
      "size" : ""
    } ]
  } ]
}

我想通过这个json数组的订单来计算总数。

methods:
    grandTotal: function(i) {
      return i.price.reduce((i) => {
        sum + i.price * i.quantity 
          return sum;
      }, 0)
    },

在grandTotal函数中,我不知道这种方法有什么问题。

<td><ul><li v-for="i in order.item"> {{i.name}} ({{i.size}}) {{i.quantity}} x unit price: {{i.price}} subtotal by item: {{product(i)}}
        <li class="comment-order"><b>Bemerkung: </b>{{order.comment}}</li>
        <li>Total: {{sum}} </li>
        </ul></td>

我想计算行总数的总和,但我不明白我的功能有什么问题。

2 个答案:

答案 0 :(得分:2)

getTotalQuantity(items) {
    return items.reduce((total, item) => item.sale_return.quantity + total, 0)
  }

这里的项目是一个具有Qnuttity值的对象的数组

答案 1 :(得分:1)

假设您将整个grandTotal数组传递给order.item函数。换句话说,您需要将grandTotal传递到// Fixed reduce function which takes in an Array and returns sum var grandTotal = function(arr) { return arr.reduce((sum, i) => { return sum + (i.price * i.quantity) }, 0) }; var obj = { "orders": [null, { "comment": "Bitte, Lassen Sie die Pizza geschnitten.", "date": "2018-06-01 07:22:10", "item": [{ "name": "Tomatensuppe", "price": 3.9, "quantity": 2, "size": "" }, { "name": "Estragoncremesuppe", "price": 4.5, "quantity": 1, "size": "" }] }, { "comment": "Geben Sie Brot dazu", "date": "2018-03-19 15:22:20", "item": [{ "name": "Minestrone", "price": 3.9, "quantity": 3, "size": "" }, { "name": "Tomatensuppe", "price": 3.9, "quantity": 2, "size": "" }] }] }; var extractedObj = [{ "name": "Minestrone", "price": 3.9, "quantity": 3, "size": "" }, { "name": "Tomatensuppe", "price": 3.9, "quantity": 2, "size": "" }] console.log(grandTotal(extractedObj));函数。相应地修改您的Vue代码。

{{1}}