Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda