首页 > 解决方案 > 将对象值减去数组不正确

问题描述

我正在尝试对数组对象的总价格求和,然后在该数组之外添加总价格。

例子 :

[
  {
    "addons": [
      {
        "title": "خبز بعجين",
        "price": 0.1,
        "selected": true
      },
      {
        "title": "لحم بعجين ",
        "price": 2,
        "selected": true
      },
      {
        "title": "ببسي بارد",
        "price": 55,
        "selected": true
      },
      {
        "title": "كولا ",
        "price": 4,
        "selected": true
      }
    ],
    "Totaladdons": 61.1, // < total price of array above . 
    "price" : 300  // < sum Totaladdons with this object price . 
  }

]

  sum(data) {
    let totalPrice = 0;
    let currency: any

    currency = this.items_local[data.index].addons.map(curr => parseFloat(curr.price)).reduce((a, b) => a + b, 0)
    console.log(currency);
    this.items_local[data.index].Totaladdons = Number(currency);
    if (this.items_local[data.index].Totaladdons) {
      totalPrice = Number(this.items_local[data.index].Totaladdons) + Number(this.items_local[data.index].price)
      this.items_local[data.index].price = totalPrice.toFixed(2)

    }
  }

删除元素数组对象然后恢复总价的减法

 minus(data) {

    if (this.items_local[data.index].addons.length > 0) {
      for (var i = this.items_local[data.index].addons.length - 1; i >= 0; i--) {

        if (this.items_local[data.index].addons[i].title === data.addon.title) {
          this.items_local[data.index].addons.splice([i], 1);

           // here l am try to resuming the price of array object
          currency = this.items_local[data.index].addons.map(curr => parseFloat(curr.price)).reduce((a, b,) => a - b, 0);
          console.log(currency);

            if (this.items_local[data.index].Totaladdons) {
              this.items_local[data.index].Totaladdons = Number(currency);
              totalPrice = Number(this.items_local[data.index].price) - Number(this.items_local[data.index].Totaladdons)
              this.items_local[data.index].price = totalPrice.toFixed(2)
            }
        }
      }

    }

  }

问题是当我点击减法时,他没有给我正确的总数。

标签: javascript

解决方案


推荐阅读