javascript - 函数中的reduce()计算产品总数

标签 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>

我想计算行总数的总和,但我不明白我的函数出了什么问题。

最佳答案

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

这里的items是具有数量值的对象数组

关于javascript - 函数中的reduce()计算产品总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50729169/

相关文章:

javascript - 隔离指令范围但保留对 ngModel 的绑定(bind)

javascript - 如何在同一个 onchange 事件期间在两个 javascript 命令之间暂停

javascript - 在 <p> 元素中插入 <span>

c# - 使用 CURL 发送到 Azure 函数的 Newtonsoft 反序列化 JSON 时出现异常

c# - 解析带有 Html 内容的 Json 字符串

javascript - 如何将值从一个变量绑定(bind)到其他变量

javascript - 通过 AJAX 将 HTML 表转换为 JSON 文件

java - Jersey 将空列表和单元素列表序列化为数组

javascript - 按下按钮后,Vue.js 动态渲染 bootstrap-vue 组件

vue.js - 页面查询在 Gridsome 的组件内部不起作用