我现在想做的是,如果用户选择了相同的项,则更新存储的数据。
例如
我已经储存了
[{
"id": "1",
"name": "soap A",
"quantity": "10",
"price" : "50.00"
},
{
"id": "2",
"name": "soap X",
"quantity": "10",
"price" : "50.00"
}]
用户再次选择了带有
id
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));