如果选择了新数据,如何从本地存储更新数据 [英] How to update data from localstorage if new data selected exists

查看:126
本文介绍了如果选择了新数据,如何从本地存储更新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如 我已经存储了

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

,然后用户再次选择id1(即"soap A")且数量为"15"的商品,我的当前结果如下所示:

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

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

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

推荐答案

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

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

这篇关于如果选择了新数据,如何从本地存储更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆