How to update data from localstorage if new data selected exists

↘锁芯ラ 提交于 2019-12-24 10:32:17

问题


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 wanted to do now is to update the stored data if the user selected the same item.

For example I have already stored

[{
 "id": "1",
 "name": "soap A",
 "quantity": "10",
 "price" : "50.00"
},
{
 "id": "2",
 "name": "soap X",
 "quantity": "10",
 "price" : "50.00"
}]

and the user again selected the the item with an id of 1 (which is "soap A") and the quantity is "15", my current result looks like this

[{
     "id": "1",
     "name": "soap A",
     "quantity": "10",
     "price" : "50.00"
    },
    {
     "id": "2",
     "name": "soap X",
     "quantity": "10",
     "price" : "50.00"
    },
    {
     "id": "1",
     "name": "soap A",
     "quantity": "15",
     "price" : "50.00"
    }]

What I wanted to do is to update if an object with the same ID exists on my local storage. it would look like this

[{
     "id": "1",
     "name": "soap A",
     "quantity": "25",
     "price" : "50.00"
    },
    {
     "id": "2",
     "name": "soap X",
     "quantity": "10",
     "price" : "50.00"
    }]

and here is my script for inserting to local storage.

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
    var newItem = {
          'id' : $('#itemId').val(),
          'name': $('#productName').val(),
          'quantity': $('#quantity').val(),
          'price': $('#productPrice').val(),

      };
       oldItems.push(newItem);

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

回答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));


来源:https://stackoverflow.com/questions/52215389/how-to-update-data-from-localstorage-if-new-data-selected-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!