簡體   English   中英

檢查本地存儲中是否已存在產品 ID

[英]check if product id already exists in localstorage

伙計們,我在 angular 中有一個購物車,我的代碼將添加的產品保存在 localstorage 中,我希望我的代碼能夠訪問“購物車”並查看該項目是否已通過 id 在 localstorage 中存在

我嘗試了這段代碼,但沒有成功,我想要一些想法,誰能幫助我

const retrieverObject: string = localStorage.getItem('cart') || '';
const retrieveObject: Array<any> = retrieverObject ? JSON.parse(retrieverObject) : [];
console.log(retrieveObject)
let presentItem = retrieveObject.find(iteml => iteml.id === item.id);

if (presentItem) {
  console.log('id already exists in localstorage')
} else {
  console.log('id not in localstorage')
}

我認為問題是我無法訪問購物車項目數組

在此處輸入圖像描述

您應該在localStorage中獲取節點item內的元素。 我可以看到您的localStorage將您的項目保存在關鍵item

偽代碼

const retrieverObject: string = localStorage.getItem('cart') || '';
const retrieveObject: Array<any> = retrieverObject ? JSON.parse(retrieverObject)?.item : [];
console.log(retrieveObject)
let presentItem = retrieveObject.find(iteml => iteml.id === item.id);

if (presentItem) {
  console.log('id already exists in localstorage')
} else {
  console.log('id not in localstorage')
}

retrieveObject項目中存在item屬性

let presentItem = retrieveObject.item.find(iteml => iteml.id === item.id);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM