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
CodePudding user response:
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')
}
CodePudding user response:
in retrieveObject
items exists in item
property
let presentItem = retrieveObject.item.find(iteml => iteml.id === item.id);