Search code examples
javascriptscopeangular7calculation

How to calculate the sum of several total amounts?


I have an array of objects in which I am creating properties that I need to display in the html. This is the structure of one of the objects in the array

 {
    "functional_id": "201911291131250012400000SD4AYAA1",
    "transactions": [
      {
        "quantity": 2,
        "price": 140,
        "item": {
          "name": "Carton de 10 coffrets",
          "description": "+ 2 recharges d'argile offertes",
          "product": {
            "name": "Coffret empreinte rouge"
          }
        },
        "amount": 280
      },
      {
        "quantity": 2,
        "price": 17,
        "item": {
          "name": "1 lanterne d'accueil + 1 accroche porte",
          "product": {
            "name": "Lanterne d'accueil",
            "description": "Lors d'une euthanasie, cette affichette verticale auto-éclairée par bougie LED, est disposée à l’accueil. Elle montre l’importance de ce moment pour votre clinique. <br /> Les accroches porte déposés sur les poignées des salles de consultation invitent au calme."
          }
        },
        "amount": 34
      },
      {
        "quantity": 1,
        "price": 0,
        "item": {
          "name": "Petit modèle",
          "description": "Par 25",
          "product": {
            "name": "Sacs blancs",
            "description": "Pour les crémations Plurielles"
          }
        },
        "amount": 0
      },
      {
        "quantity": 1,
        "price": 0,
        "item": {
          "name": "Moyen modèle",
          "description": "Par 20",
          "product": {
            "name": "Sacs blancs",
            "description": "Pour les crémations Plurielles"
          }
        },
        "amount": 0
      },
      {
        "quantity": 1,
        "price": 0,
        "item": {
          "name": "Grand modèle",
          "description": "Par 10",
          "product": {
            "name": "Sacs blancs",
            "description": "Pour les crémations Plurielles"
          }
        },
        "amount": 0
      },
      {
        "quantity": 2,
        "price": 0,
        "item": {
          "product": {
            "name": "Carnet de conventions"
          }
        },
        "amount": 0
      }
    ],
    "date": "29/11/2019",
    "order_number": "113125"
  }

at this point I create a property 'amount' for each 'transaction' to calculate the total amount of the purchase of each product.

    public inicializeData() {

        this.loaderService.eLoader.emit(true);
        this.cartsSubscription = this.cartsService.getCarts().subscribe(carts => {
            this.orders = carts;
            this.orders.forEach(cart => {
                const day = cart.functional_id.substring(6, 8);
                const month = cart.functional_id.substring(4, 6);
                const year = cart.functional_id.substring(0, 4);
                cart.date = day + '/' + month + '/' + year;
                cart.order_number = cart.functional_id.substring(8, 14);
                cart.transactions.forEach(item => {
                    item.amount = item.quantity * item.price;
                });
            });
            this.load = true;
            this.loaderService.eLoader.emit(false);
        });
    }



The problem is that I would also need a total amount for all the transactions but I cannot calculate this total. First I declare a class variable with a value of 0 and at the point where I calculate the 'item.amount' I add them all up.

public amount = 0;

 public inicializeData() {

        this.loaderService.eLoader.emit(true);
        this.cartsSubscription = this.cartsService.getCarts().subscribe(carts => {
            this.orders = carts;
            this.orders.forEach(cart => {
                const day = cart.functional_id.substring(6, 8);
                const month = cart.functional_id.substring(4, 6);
                const year = cart.functional_id.substring(0, 4);
                cart.date = day + '/' + month + '/' + year;
                cart.order_number = cart.functional_id.substring(8, 14);
                cart.transactions.forEach(item => {
                    item.amount = item.quantity * item.price;
                    this.amount += item.amount;
                });
            });
            this.load = true;
            this.loaderService.eLoader.emit(false);
        });
    }



and I see that what I get is the total of all the transactions. Which is not desired.

I understand it's a scope problem. But I also tried to declare the variable inside the last forEach, but it didn't work either.

    public inicializeData() {

        this.loaderService.eLoader.emit(true);
        this.cartsSubscription = this.cartsService.getCarts().subscribe(carts => {
            this.orders = carts;
            this.orders.forEach(cart => {
                const day = cart.functional_id.substring(6, 8);
                const month = cart.functional_id.substring(4, 6);
                const year = cart.functional_id.substring(0, 4);
                cart.date = day + '/' + month + '/' + year;
                cart.order_number = cart.functional_id.substring(8, 14);
                cart.transactions.forEach(item => {
                    item.amount = item.quantity * item.price;
                    let overallAmount = 0;
                    overallAmount += item.amount;
                });
            });
            this.load = true;
            this.loaderService.eLoader.emit(false);
            console.log(JSON.stringify(this.orders));
        });
    }

What I would need is that in the example object I could create a property that was the sum of all the item.amount (in this case it would be overallAmount = 314).

Someone to make me see my mistake. Thank you very much in advance


Solution

  • in this line this.amount += item.amount; try and do

    const cal = item.quantity * item.price;
                item.amount=cal
                this.amount += cal;
    

    or

    var amount=[]
    const cal = item.quantity * item.price;
                    item.amount=cal
                    var.push(cal)
    amount=amount.reduce((a,b)=>{return a+b})
    

    If you prefer to add a property transaction amount to your object you can use this

    t=0
    x= cart.transactions.filter(x=>cart['transac-amount']=t+=x.amount)
    console.log(cart)
    

    it will add a transaction amount to your object