[英]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.