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

422
Visualizações
How to save an array of objects in localStorage? Getting TypeError: push is not a function

I am trying to push player data (object) in an array, then save into localStorage, but I can't get it working even if I initialize the array. On the first run I got the data, but on the next runs the array is not recognised. Does anyone know what is going on? Here is my code:

  function handleRanking() {
    console.log('run function');
    let prevRanking = localStorage.getItem('ranking');
    if (prevRanking === null) {
      console.log('null value');
      prevRanking = [];
    }
    const player = {
      name,
      score: total,
      picture: gravatarEmail,
    };
    if (Array.isArray(prevRanking)) {
      prevRanking.push(JSON.stringify(player));
      localStorage.setItem('ranking', prevRanking);
    } else {
      console.log('not an array');
    }
  }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

One thing to know right away is that localStorage can only save strings. Therefore when you want to save a non string value, you need to call JSON.stringify(data) before saving, and JSON.parse(data) after getting the data and before using it.

In your case, an easy way is to add the player and then save prevRanking as string. But before you should parse what you get as it is always a string if not null.

  function handleRanking() {
    console.log('run function');
    let prevRanking = localStorage.getItem('ranking');
    if (prevRanking === null) {
      console.log('null value');
      prevRanking = [];
    }else{
     prevRanking = JSON.parse(prevRanking);
    }
    const player = {
      name,
      score: total,
      picture: gravatarEmail,
    };
    if (Array.isArray(prevRanking)) {
      prevRanking.push(player);
      localStorage.setItem('ranking', JSON.stringify(prevRanking));
    } else {
      console.log('not an array');
    }
  }
about 4 years ago · Juan Pablo Isaza Relatório

0

After you have retrieved the info from the localStorage you need to pass it into the JSON.parse method. Because when storing information in the localstorage it is saved as string.

function handleRanking() {
    console.log('run function');
    let prevRanking = localStorage.getItem('ranking');
    if (prevRanking === null) {
      console.log('null value');
      prevRanking = [];
    }
    prevRanking = JSON.parse(prevRanking); // added it in here so prevRanking is definetly defined
    const player = {
      name,
      score: total,
      picture: gravatarEmail,
    };
    if (Array.isArray(prevRanking)) {
      prevRanking.push(JSON.stringify(player));
      localStorage.setItem('ranking', JSON.stringify(prevRanking));
    } else {
      console.log('not an array');
    }
  }
about 4 years ago · Juan Pablo Isaza Relatório

0

Because the value of a key gets from LocalStorage is a string. So, you have to JSON.parse before pushing. https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#parameters

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