如果存在选定的新数据,如何从localstorage更新数据

问题描述 投票:1回答:1

我正在创建一个订购系统,用户将选择一个项目并将其添加到购物车。我使用本地存储来保存所选项目并在下一页上获取这些项目。

我现在想做的是,如果用户选择了相同的项目,则更新存储的数据。

例如,我已经存储了

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

并且用户再次使用id1)的"soap A"选择了该项目,数量为"15",我当前的结果如下所示

[{
     "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"
    }]

我想要做的是更新我的本地存储上是否存在具有相同ID的对象。它看起来像这样

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

这是我插入本地存储的脚本。

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));
javascript jquery json local-storage
1个回答
3
投票

你需要find匹配当前数组中的id(如果存在)。如果是,则分配给该元素 - 否则,推送一个新元素。

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));
© www.soinside.com 2019 - 2024. All rights reserved.