【问题标题】:How to update data from localstorage if new data selected exists如果选择的新数据存在,如何从本地存储更新数据
【发布时间】:2018-09-07 13:49:50
【问题描述】:

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

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

例如 我已经收藏了

[{
 "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】:

    如果存在,您需要在当前数组中为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));
    

    【讨论】:

    • 另外,如果他愿意,他可以添加数量:'quantity': existingItem.quantity + $('#quantity').val(),
    • 我想通过 id 而不是 name 搜索匹配元素可能会更好,因为 id 应该是唯一的。
    • 我尝试使用 id 替换它。并尝试 console.log existingItem 但返回 undefined。
    • @LionSmith 如果没有existingItem,那么您需要创建一个新项目,而不是像答案中的代码那样尝试分配给existingItem
    • 我已经创建了一个新项目并尝试使用现有数据添加另一个项目。但发生的事情不是更新它插入的现有数据。所以我所做的是检查existingItem,它返回未定义..
    猜你喜欢
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2013-08-09
    • 2021-12-10
    相关资源
    最近更新 更多