I’m creating a shopping cart where in if I add to cart, the quantity should be added to the previous quantity. In my case it only sets to a quantity and is not adding.
Here is the code that I tried:
var addNewItem = function (name, quantity, price) {
// retrieve it (Or create a blank array if there isn't any info saved yet),
var items = JSON.parse(localStorage.getItem('itemsInCart')) || [];
// add to it,
items.push({name: name, quantity: quantity, price: price});
//supposed to add to quantity
for (var item of items){
if(item.name === name){
quantity += item.quantity ;
console.log('true');
}
}
// then put it back.
localStorage.setItem('itemsInCart', JSON.stringify(items));
console.log(items);
}
Advertisement
Answer
Just needed a slight modification to the addition logic.
You need to check if it already exists in the itemsInCart array before pushing it.
var addNewItem = function(name, quantity, price) {
// retrieve it (Or create a blank array if there isn't any info saved yet),
var items = JSON.parse(localStorage.getItem('itemsInCart')) || [];
// add to it, only if it's empty
var item = items.find(item => item.name === name);
if (item) {
item.quantity += quantity;
} else {
items.push({
name,
quantity,
price
})
}
// then put it back.
localStorage.setItem('itemsInCart', JSON.stringify(items));
console.log(items);
}