[Vuejs]-How to loop through an array of data inside methods VueJs

2👍

Please learn how to provide a minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example
Ideally provide a jsfiddle or codesandbox demonstrating your problem.

You shouldn’t change something that was passed in as a prop (read up on "one way flow").

Either have your orders array as a local data object in the current component or $emit an addToCart event from this component and handle the actual adding to cart in the parent by listening to this event.

Assuming your orders are in the local data object:

data() {
   return {
     orders: [
       { id: 'exists', quantity: 1 }
     ]
   }
},
methods: {
  addToCart(product) {
     let exists = this.orders.find(p => p.id == product.id)
     if(exists == -1) { // doesn't exists yet
       this.orders.push(product)
     } else {
       this.orders[exists].quantity++
     }
  }
}

0👍

Check the value in orders, if it is returning you array having length more than 0 it means product is already added else product is not present.

<template>
      <div v-for="(product,index) in products" :key="index">
       <div>Name : {{ product.name }} </div>
      </div>
      <button @click="handleAdd({id:20})">Add</button>
    </template>
    
    
    props: {
      products: Array,
     orders: Array,
     }
     methods: {
       handleAdd(product){
        
          const check = this.orders.filter(item => item.id === product.id) 
          
          if(check.length === 0){
            orders.push(product)
          } else {
           // other thing
           }
        
      }
     }

Leave a comment