I’m creating a shopping cart and when I want to add an element to the cart it adds the name and quantity just as many times as I click the add button, but what I want is the name added only one time and just the quantity increased as I click the add button. I can’t use inbuilt methods. I have try many ways but I can’t figure how to do it. Any idea? I think it must be very simple but can’t solve it.
So what I get now is this:
[ "geranios1", "geranios2", "rosas1", "rosas2", "ranunculos1", "geranios3", "calatheas1", "singonios1" ]
And what I want is this:
geranios: 3
rosas: 1
ranunculos: 4
This is my code:
<button @click="mostrarLista(objeto.nombrePlanta)"
const app=new Vue({
el: '#app',
data: {
listaFlores: [],
plantasAgregar:[
{nombrePlanta: 'rosas', cantidad: 0, stock: 5},
{nombrePlanta: 'ranunculos', cantidad: 0, stock: 3},
{nombrePlanta: 'geranios', cantidad: 0, stock: 4},
{nombrePlanta: 'calatheas', cantidad: 0, stock: 1},
{nombrePlanta: 'singonios', cantidad: 0, stock: 2}
]
},
mostrarLista(florPlant){
for(cosa of this.plantasAgregar){
if(cosa.nombrePlanta == florPlant && cosa.nombrePlanta !== this.listaFlores)
{
this.listaFlores.push(cosa.nombrePlanta + cosa.cantidad);
console.log(this.listaFlores);
}
}
}
2
Answers
The line of
pushes the name concatenated with the number. You will need to find the index of the element and increment its quantity, or, if such an index does not exist, then push it.
Example
The simple answer is to push an object to the cart array instead of a string so that you can track and display quantity of items.
To do this you can create a reactive array for each of plantasAgregar and cart and use the function called on the add to cart click to update both (add to cart, increase quantity if existing, and reduce stock in plantasAgregar). Find the index of the selected product in either array and, based on whether it exists or not, update the item in the cart or push a new entry.
The solution below uses the Composition API but should translate to the Options fairly easily, happy to help if you get stuck.