Increase Array with filter

0

I need to increment the item this.order[i].nome_service in the variable this.result only when clicking the checkbox, as well as decrement when unchecked.

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) {
  this.orders[i].qtd = (this.orders[i].qtd === "0") ? "1" : "0";

  this.result=this.orders.filter(item => item.qtd === "1").push(this.order[i].nome_service);
  console.log('result '+this.result);

  this.total = this.orders.filter(item => item.qtd === "1").reduce((a, b) => a + parseInt(b.price_service), 0);
  console.log('total = '+this.total);
}
<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>  
</div>
    
asked by anonymous 22.03.2018 / 01:45

1 answer

1

Make sure the item already exists in result

let test = this.result.filter(item => item === this.orders[i].nome_service);

Make a condition that checks whether the number of elements returned is greater than 0

(test.length) ? this.result.splice(this.result.indexOf(this.orders[i].nome_service), 1) : this.result.push(this.orders[i].nome_service);

Explanation

If it is, it is because the item was marked, then it will execute the code to remove:

this.result.splice(this.result.indexOf(this.orders[i].nome_service), 1)

Otherwise you will add the item to result

this.result.push(this.orders[i].nome_service)
  

See working at stackblitz

    
22.03.2018 / 08:56