Skip to content Skip to sidebar Skip to footer

How To Update Data From Localstorage If New Data Selected Exists

I am creating an ordering system which a user will select an item and add them to cart. I use local storage to save the items selected and get those items on the next page. What I

Solution 1:

You need to find a matching id in the current array, if it exists. If so, assign to that element - otherwise, push a new element.

const oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
const idToUse = $('#itemId').val();
const existingItem = oldItems.find(({ id }) => id === idToUse);
if (existingItem) {
  Object.assign(existingItem, {
    'name': $('#productName').val(),
    'quantity': existingItem.quantity + $('#quantity').val(),
    'price': $('#productPrice').val(),
  })
} else {
  const newItem = {
    'id' : idToUse,
    'name': $('#productName').val(),
    'quantity': $('#quantity').val(),
    'price': $('#productPrice').val(),

  };
  oldItems.push(newItem);
}

localStorage.setItem('itemsArray', JSON.stringify(oldItems));

Post a Comment for "How To Update Data From Localstorage If New Data Selected Exists"