Reputation: 79
I want to check if a id exist in database it will just simply replace it. When i try to do that it is adding the same id.
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":44,"productName":"Cleansing milk with Toner","productCost":"140","productQty":"1"},{"productId":44,"productName":"Cleansing milk with Toner","productCost":"280","productQty":"2"},{"productId":44,"productName":"Cleansing milk with Toner","productCost":"420","productQty":"3"}]
output I want
[{"productId":44,"productName":"Cleansing milk with Toner","productCost":"280","productQty":"2"},{"productId":43,"productName":"Hair Spa 100 gm","productCost":"160","productQty":"1"}]
Upvotes: -1
Views: 432
Reputation: 502
you need to check if the product is already located
in localStorage
if so get it index and replace it and if not just append it to the product_list
try this
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'))
const DuplicatedIndex = product_list.findIndex(product => product.productId == productId)
if(DuplicatedIndex == -1) {
product_list.push({productId,productCost,productQty})
} else {
product_list[DuplicatedIndex] = {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}]))
}
}
Upvotes: 3
Reputation: 11
Before pushing the new item into product_list
, you should check if that list has the item whose productId
equals to productId
and then replace it with the new item or just push that item.
I will put the correct code below:
const index = product_list.findIndex(item => item.productId === productId);
if(index === -1) {
product_list.push({productId,productCost,productQty});
} else {
product_list[index] = {productId,productCost,productQty};
}
Upvotes: 2