javascript - 如果选择的新数据存在,如何从本地存储更新数据
问题描述
我正在创建一个订购系统,用户将选择一个项目并将它们添加到购物车。我使用本地存储来保存选定的项目并在下一页上获取这些项目。
如果用户选择了相同的项目,我现在想做的是更新存储的数据。
例如我已经存储了
[{
"id": "1",
"name": "soap A",
"quantity": "10",
"price" : "50.00"
},
{
"id": "2",
"name": "soap X",
"quantity": "10",
"price" : "50.00"
}]
并且用户再次选择了带有id
of 1
(即"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));
解决方案
如果存在,您需要在当前数组中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));
推荐阅读
- oauth-2.0 - Spring Boot + Security OAuth2.0 Client with Custom Provider
- groovy - GEB: Disable implicit assertions in waitFor block
- c# - How to fill a wpf tree view using mvvm from a model with "infinte" levels
- c# - How to pass a plus sign in a string from a view to controller?
- c# - 我如何从这个模拟服务中获得结果?
- react-select - 聚焦时如何删除 MultiValueRemove 上的红色背景
- xml - 读取从navison收到的xml响应并将响应绑定在mvc模型中并显示在表格中
- java - Kafka Streams - 偏移提交失败。请求超时
- mongodb - Mongo Views 计数太慢
- node.js - jti 声明应该多久重新生成一次?