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

140
Visualizações
javascript I don't know how to get a specific object with getItem

I want to get only accessToken value 123 inside Object in value in localStorage . I don't know how to get it.

key : stackoverflow 

value : 
{
  "accessToken": "123",
  "expiresAt": "2022-07-20T03:13:31.736756085Z",
  "refreshToken": "456"
}

I've tried it myself and it doesn't work.

console.log(window.localStorage.getItem("stackoverflow", 'accessToken'))

Isn't this the way to get it?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The problem here is the value saved as json so you need to parse it first using JSON.parse() like this

let parsedData = JSON.parse(window.localStorage.getItem("stackoverflow"))
console.log(parsedData.accessToken)
about 4 years ago · Santiago Trujillo Relatório

0

You need to store the object as a JSON

// SET
localStorage.setItem('stackoverflow', JSON.stringify(stackoverflow));

Then get it and parse it

// GET
let stackoverflow = localStorage.getItem('stackoverflow');
stackoverflow = JSON.parse(stackoverflow);

And finally you can get the property of stackoverflow object

const accessToken = stackoverflow.accessToken;
about 4 years ago · Santiago Trujillo Relatório

0

Before saving the data, you must convert an object into a string, because localstorage only support string type, and whenever you want to get that object data, you must parse that data and then you can access object data

localStorage.setItem(
      'stackoverflow',
      JSON.stringify({
        accessToken: '123',
        expiresAt: '2022-07-20T03:13:31.736756085Z',
        refreshToken: '456',
      })
);
const stackoverflow: any = localStorage.getItem('stackoverflow');  
const obj = JSON.parse(stackoverflow);
console.log(obj.accessToken);
about 4 years ago · Santiago Trujillo 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