I'm currently working on a restaurant menu project where each item is an object with properties such as name, id (which is autogenerated), quantity, and options. Each option includes size and price values nested within an array.
My goal is to allow users to add items to their shopping cart while ensuring that duplicate items are not added. However, I'm facing a challenge because each item has a unique id, but can come in multiple sizes.
Below is a snippet of my code:
export default {
data(){
return {
cart: []
}
}
//...
methods: {
addItem(pizza, options){
let selectedPizza= {
id: pizza.id,
name: pizza.name,
size: options.size,
price: options.price
quantity: 1
}
if(this.cart.length > 0) {
this.cart.forEach(item => {
if(item.name === selectedPizza.name && item.size === selectedPizza.size && item.id === selectedPizza.id) {
return item.quantity++
} else {
this.cart.push(selectedPizza)
}
})
} else {
this.cart.push(selectedPizza)
}
}
}
}
While the code above functions well for adding pizzas of the same size, it encounters issues when attempting to add the same pizza in different sizes due to the repeated id. Does anyone have a workaround or solution for this scenario? Your help is much appreciated!