检查本地存储中的重复值

Check duplicate value in localstorage

我想检查数据库中是否存在一个 ID,它只会简单地替换它。当我尝试这样做时,它添加了相同的 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}]))
  }
}

输出

[{"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"}]

输出我想要的

[{"productId":44,"productName":"Cleansing milk with Toner","productCost":"280","productQty":"2"},{"productId":43,"productName":"Hair Spa 100 gm","productCost":"160","productQty":"1"}]

在将新项目推送到 product_list 之前,您应该检查该列表是否包含 productId 等于 productId 的项目,然后将其替换为新项目或直接推送那个项目。 我将把正确的代码放在下面:

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};
}

您需要检查产品是否已经定位 在 localStorage 中,如果是,则获取索引并替换它,如果不是,则将其附加到 product_list

试试这个

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}]))
   }
}