Here I'm trying store the name of the id and the number of times it has been clicked.
It's stores as an object but when I tried JSON.Stringify()
it returns a empty array like this
'[]'
if (localStorage.getItem('cart') == null) {
var cartArr = {};
} else {
cartArr = JSON.parse(localStorage.getItem('cart'));
}
const cartClass = document.querySelectorAll(".cart");
cartClass.forEach((ele) => {
ele.addEventListener('click', (e) => {
let cartId = (e.target.getAttribute('id'));
if (cartArr[cartId] == undefined) {
cartArr[cartId] = 1;
} else {
cartArr[cartId] += 1;
}
localStorage.setItem('cart', JSON.stringify(cartArr));
console.log(localStorage.getItem('cart'));
});
});
I have checked your code, it works correctly. Your problem can be solved by cleaning your localStorage
. It seems that at some point you have stored an empty array into your local storage. What happens is, JSON.stringify
stores the contents of array, but ignores any custom properties you set on an array object:
// This will log "[]"
const arr = [];
arr.prop = "val"
console.log(JSON.stringify(arr));
// This will log {"prop": "val"}
const obj = {};
obj.prop = "val"
console.log(JSON.stringify(obj));