[Vuejs]-Vue.js, conditionally adding item to an array

2👍

Problem is in the forEach inside addItem function.Please find the updated code.

addItem(pizza, options) {
      let selectedPizza = {
        name: pizza.name,
        siza: options.size,
        price: options.price,
        quantity: 1,
        id: options.size === 'L' ? pizza.id.split('').reverse().join('') : pizza.id
      }

      if(this.cart.length > 0) {
        let exist = false;
        for(let index = 0; index < this.cart.length; index++) {
          let item = this.cart[index];
          if(item.id === selectedPizza.id && item.size === selectedPizza.size){
            item.quantity++;
            this.response ='Item already exist in the cart';
            exist = true;
            break;
          } 
        }
        if(!exist) {
            this.response = ''
            this.cart.push(selectedPizza)
        }
      } else {
        this.cart.push(selectedPizza)
        console.log('item is added to an empty cart')
      }
    }

You were adding pizzas into the cart multiple number of times inside forEach, if current iteration pizza is not equal to the selectedPizza.

Leave a comment