skip to Main Content

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


  1. some is not best suited here. find is more appropriate for this. You find and if found increment else add to cart

    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);
      const foundInCart = cart.find(e => e.id === item.id);
      if (foundInCart) {
        foundInCart.quantity += 1
        localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
      } else {
        item.quantity = 1;
        cart.push(item);
        localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
      }
    } else {
      item.quantity = 1;
      cart.push(item);
      localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
    }
    
    console.log('*******************')
    console.log(cart)
    console.log('*******************')

    jsfiddle

    Login or Signup to reply.
  2. 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:

    var item = products[Math.floor(Math.random() * products.length)]; 
    if (localStorage.getItem('ItemsInCart')) {
        var previousCartItems = localStorage.getItem("ItemsInCart");
        cart = JSON.parse(previousCartItems);
        var position = cart.map(function(object) {return object.id; }).indexOf(item.id);
        var result = cart[position];
        if(!result){  
            item.quantity = 1;
            cart.push(item);
            localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
        }else{
            let index=cart.findIndex(x => x.id === result.id)   
            cart[index].quantity++;
            localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
        }
    } else {
        item.quantity = 1;
        cart.push(item);
        localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
    }
    console.log('*******************')
    console.log(cart)
    console.log('*******************')
    
    Login or Signup to reply.
  3. 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

    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)];
      console.log(item);
      if (localStorage.getItem("ItemsInCart")) {
        var previousCartItems = localStorage.getItem("ItemsInCart");
        cart = JSON.parse(previousCartItems);
        let obj;
        let isAvailable = cart.some((o, i) => {
          if (o.id === item.id) {
            obj = o;
            return true;
          }
        });
        
        if (isAvailable) {
          obj.quantity = obj.quantity + 1;
          localStorage.setItem("ItemsInCart", JSON.stringify(cart));
        } else {
          item.quantity = 1;
          cart.push(item);
          localStorage.setItem("ItemsInCart", JSON.stringify(cart));
        }
      } else {
        item.quantity = 1;
        cart.push(item);
        localStorage.setItem("ItemsInCart", JSON.stringify(cart));
      }
      console.log("*******************");
      console.log(cart);
      console.log("*******************");
    

    jsfiddle

    Login or Signup to reply.
  4. You’re overcomplicating things.

    const item = products[Math.floor(Math.random() * products.length)];
    
    const cart = JSON.parse(localStorage.getItem("ItemsInCart")) || [];
    
    const cartItem = cart.find(cartItem => cartItem.id === item.id);
    
    if (cartItem) {
      cartItem.quantity += 1;
    } else {
      // just for good measure, if you're going to mutate this object later on, 
      // don't push the original but a copy to the cart.
      cart.push({ ...item, quantity: 1 });
    }
    
    localStorage.setItem("ItemsInCart", JSON.stringify(cart));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search