I have a array of objects having products and I’m randomly choosing items from product object and adding to cart and then storing it into local storage. here whenever I’m trying to add the product already existing in the its creating duplicate object, instead of that I want to just increment and update the quantity attribute of the product.
here is my code what I’m trying to achieve.
var cart = [];
var products = [
{
id: 1,
productDescription: "Iphone 14 pro",
price: 1544,
quantity: 1
},
{
id: 2,
productDescription: "OPPOF19",
price: 788,
quantity: 1
},
{
id: 3,
productDescription: "Microsoft Surface Laptop 4",
price: 2500,
quantity: 1
},
{
id: 4,
productDescription: "Fog Scent Xpressio Perfume",
price: 15,
quantity: 1
},
{
id: 5,
productDescription: "Hyaluronic Acid Serum",
price: 19,
quantity: 1
}
];
var item = products[Math.floor(Math.random() * products.length)];
if (localStorage.getItem('ItemsInCart')) {
var previousCartItems = localStorage.getItem("ItemsInCart");
cart = JSON.parse(previousCartItems);
let obj = cart.some((o, i) => {
if (o.id == item.id) {
cart[i].quantity = cart[i].quantity + 1;
localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
return true;
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
return true;
}
});
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
}
console.log('*******************')
console.log(cart)
console.log('*******************')
4
Answers
some
is not best suited here.find
is more appropriate for this. You find and if found increment else add to cartjsfiddle
I wouldn’t use ‘some’ for this behavior. Maybe you would like to use a function like ‘map’. This is the simplest way I can think of:
Hey in case you still want to use some array method to achieve the above you can do this by the below though map and find methods are best suited solutions
jsfiddle
You’re overcomplicating things.