Previous inquiries have delved into similar topics including Determining if an array contains a specific value and Checking for a value in an array using JavaScript, but none of them have provided a solution to my particular issue.
The comments within my code outline the specifics of what I am attempting to accomplish.
// I have initialized an empty array that will store items added via an onclick function
var list = []
// The following is my 'add to cart' function
function addToCart(productName, productPrice, url, description, quantity) {
// First check if the list is empty; if so, simply add the item to the cart without looping through
if (list.length === 0) {
list.push({ name: productName, price: productPrice, url: url, quantity: 1 });
console.log(list)
console.log('adding first item')
// If not empty, then iterate through
} else {
for (var i = 0; i < list.length; i++) {
// If the product name of the clicked item already exists in the array
// do not add it again, instead increment its quantity by 1
if (list[i].name === productName) {
list[i].quantity++
console.log('same product, no need to add - increasing quantity by 1 ')
console.log(list)
} else {
// If the clicked product does not exist in the list, add it as a new entry
// A problem arises when there is only one item in the list
// Everything functions properly when there are two different products in the list
// However, when clicking on an existing item, the quantity increments and adds the same item
list.push({ name: productName, price: productPrice, url: url, quantity: 1 });
console.log('new item added since it did not previously exist')
console.log(list)
}
}
}
}
The following are the console logs:
First click:
[{ … }]
0: { name: "Bell pepper", price: "3", url: "https://firebasestora…=media&tokenc", quantity: 1 }
length: 1
__proto__: Array(0)
Second click on the same product:
same product, no need to add - increasing quantity by 1
[{ … }]
0:
name: "Bell pepper"
price: "3"
url: "https://firebasestorage.googleapis.com/v0/b/ps-farms.appspoc"
quantity: 2
__proto__: Object
length: 1
__proto__: Array(0)
First time selecting a different product resulting in two distinct items in the list:
new item added since it did not previously exist
(2)[{ … }, { … }]
0: { name: "Bell pepper", price: "3", url: "https://firebasestoc", quantity: 2 }
1: { name: "Cucumber Poinsett/kg", price: "7.5", url: "https://firebasest", quantity: 1 }
length: 2
__proto__: Array(0)
Upon clicking on 'Cucumber Poinsett / kg' again, instead of updating the quantity, it is being added as a new entry.
This is where I am encountering issues that I cannot pinpoint:
new item added since it did not previously exist
(3)[{ … }, { … }, { … }]
0: { name: "Bell pepper", price: "3", url: "https://firebasesto/4858c", quantity: 2 }
1: { name: "Cucumber Poinsett / kg", price: "7.5", url: "https://firebasestorage.c74c", quantity: 1 }
2: { name: "Cucumber Poinsett / kg", price: "7.5", url: "https://firebasest74c", quantity: 1 }
length: 3
``