I am new to working with a shopping cart component and my code is structured like this:
let cartCount = document.getElementById("counter");
let isItemSelected = false;
let itemCount = 0;
let shoppingCart = [];
let selectedSize = "";
let displaySelectedSize = document.getElementById("selected");
let displayCart = document.getElementById("cart");
selectItem = () => {
isItemSelected = true;
selectedSize = event.srcElement.id;
displaySelectedSize.innerHTML = `${selectedSize}`;
}
addItem = () => {
if (isItemSelected === true) {
const shopItem = {
name: "Classic Tee",
price: 75,
size: `${selectedSize}`,
quantity: 0
}
itemCount += 1;
cartCount.innerHTML = `( ${itemCount} )`;
shopItem.quantity++;
shoppingCart.push(shopItem);
console.log(shoppingCart);
return itemSuccess();
} else {
return itemError();
}
}
My goal is for the shopItem.quantity to increase if I have multiple of the selected size.
Currently, I am getting this output:
// Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
1: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
// Desired Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 2}
I understand why my output looks like that, as a new object is created each time my addItem function runs. However, I want to update my shopItem.quantity if there are duplicates...
How can I achieve that?