简体   繁体   中英

check if product id already exists in localstorage

guys i have a shopping cart in angular my code saves the added products in localstorage, I would like my code to be able to access the 'cart' and see if the item already exists in localstorage by id

I tried this code, but without success, I would like ideas, who can help me

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

I think the problem is that I can't access the cart item array

在此处输入图像描述

You should take the elements inside the node item inside the localStorage . I could see that your localStorage holds your items inside the key item

Pseudo Code

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

in retrieveObject items exists in item property

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM