If the value is exist in localstorage I want to replace it. When I try to do that existing value is still inserting.
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}]))
}
}
Output
[{"productId":43,"productCost":"320","productQty":"2"},{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
When I want to insert same value I want the output to be
[{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
CodePudding user response:
To avoid that you push the same product a second time, first filter out the object that might concern the same product:
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));