Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
Not getting the output for JSON.strigify()

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'));
  });
});
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your code should work. You never stored an array in that code. Perhaps you have another code that stored cart as an array?

I would delegate and give the system a tiny bit of time to react

const cartStr = localStorage.getItem('cart')
cartArr = cartStr ? JSON.parse(cartStr) : {}
const cartContainer = document.getElementById("cartContainer");
cartContainer.addEventListener('click', (e) => {
  const tgt = e.target.closest(".cart");
  if (tgt) {
    let cartId = tgt.id;
    cartArr[cartId] = cartArr[cartId] ? cartArr[cartId] : 0;
    cartArr[cartId]++;
    localStorage.setItem('cart', JSON.stringify(cartArr));
    setTimeout(function() {
      console.log(localStorage.getItem('cart'))
    }, 10); // give the system time to react
  }
});

about 4 years ago · Juan Pablo Isaza Report

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!