Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda