Increment Array with filter

Asked

Viewed 90 times

0

I need to increment the item this.order[i].nome_servicein the variable this.result only when you click 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>

1 answer

1


Check if 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 returned elements 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 so, 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 it will add the item in result

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

See working in stackblitz

Browser other questions tagged

You are not signed in. Login or sign up in order to post.