如何使用 javascript 替换 localstorage 中的值?
How to replace a value in localstorage using javascript?
如果本地存储中存在该值,我想替换它。当我尝试这样做时,现有值仍在插入。
addEntry = (e,id) => {
e.preventDefault()
let product_list = []
let productCost = document.getElementById('projectcost').value;
let productQty = document.getElementById('productQty'+id).value;
let productId = id;
if(localStorage.getItem('myItems')){
product_list = JSON.parse(localStorage.getItem('myItems'))
product_list.push({productId,productCost,productQty})
localStorage.setItem('myItems',JSON.stringify(product_list))
}else{
product_list.push({productId,productCost,productQty})
localStorage.setItem('myItems',JSON.stringify([{productId,productCost,productQty}]))
}
}
输出
[{"productId":43,"productCost":"320","productQty":"2"},{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
当我想插入相同的值时,我希望输出为
[{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
为避免再次推送同一个产品,请先过滤掉可能涉及同一个产品的对象:
let productCost = +document.getElementById('projectcost').value;
let productQty = +document.getElementById('productQty'+id).value;
let product_list = JSON.parse(localStorage.getItem('myItems') ?? "[]");
.filter(({productId}) => productId != id)
.concat({productId: id, productCost, productQty});
localStorage.setItem('myItems', JSON.stringify(product_list));
如果本地存储中存在该值,我想替换它。当我尝试这样做时,现有值仍在插入。
addEntry = (e,id) => {
e.preventDefault()
let product_list = []
let productCost = document.getElementById('projectcost').value;
let productQty = document.getElementById('productQty'+id).value;
let productId = id;
if(localStorage.getItem('myItems')){
product_list = JSON.parse(localStorage.getItem('myItems'))
product_list.push({productId,productCost,productQty})
localStorage.setItem('myItems',JSON.stringify(product_list))
}else{
product_list.push({productId,productCost,productQty})
localStorage.setItem('myItems',JSON.stringify([{productId,productCost,productQty}]))
}
}
输出
[{"productId":43,"productCost":"320","productQty":"2"},{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
当我想插入相同的值时,我希望输出为
[{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
为避免再次推送同一个产品,请先过滤掉可能涉及同一个产品的对象:
let productCost = +document.getElementById('projectcost').value;
let productQty = +document.getElementById('productQty'+id).value;
let product_list = JSON.parse(localStorage.getItem('myItems') ?? "[]");
.filter(({productId}) => productId != id)
.concat({productId: id, productCost, productQty});
localStorage.setItem('myItems', JSON.stringify(product_list));