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"}]
CodePudding user response:
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};
}
CodePudding user response:
const find = product_list.find(x => x.productId === productId);
if(find != null && find != undefined){
product_list.forEach(e =>{
if(e.productId = productId){
e.productQty = productQty;
e.productCost = productCost;
}
});
}