I'm new to JS. I have product details as objects. I need to update my cart array on the click,
if (cart=== null)=> qty = 1 => push to cart array ;
else if ( same name && same lense ) => updating qty+1; (bcz there is a item that fulfill that condition) ;
else if ( same name && different lense ) => qty = 1;=> then push to cart array;
else ( different name && different lense ) => qty = 1;=> then push to cart array;
But when I push ( same name && same lense ), supposed to update ( same name && same lense )'s items qty. but it is updating the index[0]'s qty only. How should i solve this?
This is my cart array
let cart = JSON.parse(localStorage.getItem('productArray')) || [];``
> //new item object//
>//lense client has severel option//
const cartItem = {
pic: singlePic.src,
name: singleProductName.textContent,
qty: 0,
price: singleProductPrice,
lense: "",
};
function addToCart() {
//no item
if (JSON.parse(localStorage.getItem('productArray')) == null) {
//update the cart
cartItem.qty = 1;
//push to the cart
cart.push(cartItem);
localStorage.setItem('productArray', JSON.stringify(cart))
// update the cart after the condition
cart = JSON.parse(localStorage.getItem('productArray'))
} else {
// cart has some items
for (let oldItem of cart) {
if (cart.some(oldItem => oldItem.name === cartItem.name && oldItem.lense === cartItem.lense)) { oldItem.qty += 1
// replace order with updated cart
localStorage.setItem("productArray", JSON.stringify(cart));
cart = JSON.parse(localStorage.getItem("productArray"))
}
else if (cart.some(oldItem => oldItem.name === cartItem.name && oldItem.lense !== cartItem.lense)) {
cartItem.qty = 1
cart.push(cartItem)
localStorage.setItem('productArray', JSON.stringify(cart))
cart = JSON.parse(localStorage.getItem("productArray"))
}
else {
cartItem.qty = 1
cart.push(cartItem)
localStorage.setItem('productArray', JSON.stringify(cart))
cart = JSON.parse(localStorage.getItem("productArray"))
}
}
}
Without knowing too much about your application needs, here's a basic implementation of updating a collection.
This type of application is usually handled by an API. But this will definitely point you in the right direction