Calculate and Decrease Values in Array

1

I'm trying to decrement and calculate values from an unsuccessful array. The decrementation works to a certain extent, then decrements different values from what is clicked on the checkbox and the calculation appears on the console as NaN.

orders = [
{id_service: "1", id_empresa: "9", nome_service: "Servico 01", qtd: "0", checkup: "false", price_service : "250"},

{id_service: "2", id_empresa: "9", nome_service: "Servico 02", qtd: "0", checkup: "false" price_service : "300"},

{id_service: "3", id_empresa: "9", nome_service: "Servico 03", qtd: "0", checkup: "false" price_service : "400"}
]

calc(i) {
  let obj = JSON.parse(this.orders[i].price_service);


  if (this.orders[i].qtd == 0) {
    this.result.push(obj);
    this.orders[i].qtd = 1;
  }
  else {
    this.result.splice(i, 1);
    this.orders[i].qtd = 0;
  }
  this.result.reduce(function (a, b) {
    return a + b['obj'];
  }, 0);
  
}
<div *ngFor="let item of orders; let i = index; ">
    <ion-item>
      <ion-label class="title">{{item.nome_service}}
        <span>{{item.price_service}}</span>
      </ion-label>
      <ion-checkbox (click)="calc(i)" checked="{{item.checkup}}" color="green"></ion-checkbox>
    </ion-item>
    <p>{{result}}</p>
  </div>
    
asked by anonymous 19.03.2018 / 03:10

1 answer

1

Since the intention is to add the value of price_service of all items containing the qtd property to 1, there is no need to create a new object. Just filter the orders object using the filter and retrieve all items that contain the qtd q property equal to 1, then use the reduce .

I took the liberty of making some modifications, to make it easier, I removed all the double quotation marks of the properties that are of type number and Boolean.

orders = [
  { id_service: 1, id_empresa: 9, nome_service: "Servico 01", qtd: 0, checkup: false, price_service: 250 },
  { id_service: 2, id_empresa: 9, nome_service: "Servico 02", qtd: 0, checkup: false, price_service: 300 },
  { id_service: 3, id_empresa: 9, nome_service: "Servico 03", qtd: 0, checkup: false, price_service: 400 }
];

Create a variable to store the sum value:

total: number = 0;

Your calc method looks like this:

calc(i) {
  this.orders[i].qtd = (this.orders[i].qtd === 0) ? 1 : 0;
  this.total = this.orders.filter(item => item.qtd === 1).reduce((a, b) => a + b.price_service, 0);
  console.log(this.total);
}

Explanation

When you run this.orders.filter(item => item.qtd === 1) , a new array is returned with the elements that passed the test implemented by the supplied method, which in this case is: item => item.qtd === 1 .

In the reduce method, the sum of the value of a with the value of property price_service of element b .

  

You can see it working at stackblitz

    
20.03.2018 / 08:50