Search code examples
javascriptangulartypescriptlocal

How to get the value from the localStorage object key? Angular


I need your help. In localStorage I have the object in the example. I am using Angular. I need to extract the value of the first linkedinMail key. I tried to do it in several ways, but as a result in the console, I get the first curly brace {

Object fron localStorage

{"linkedinMail": "mail.com", "password": "123"}

The first option:

public linkedinEmailBody: any

const emailLoginLinkedin = localStorage.getItem('credsForJetLeadBE')
let [key, value] = Object.entries(emailLoginLinkedin)[0];
this.linkedinEmailBody = value;
console.log(this.linkedinEmailBody) // result: `{`

The second option:

public linkedinEmailBody: any

const emailLoginLinkedin = localStorage.getItem('credsForJetLeadBE')
const valueEmailLinkedin = Object.values(emailLoginLinkedin)[0];
this.linkedinEmailBody = valueEmailLinkedin
console.log(this.linkedinEmailBody) // result: `{`

The third option

public linkedinEmailBody: any

const emailLoginLinkedin = localStorage.getItem('credsForJetLeadBE')
const valueEmailLinkedin = emailLoginLinkedin[Object.keys(emailLoginLinkedin)[0]];
this.linkedinEmailBody = valueEmailLinkedin
console.log(this.linkedinEmailBody) // result: `{`

When I use standard JS, the value of the linkedinMail field comes to me fine, instead of {. What am I doing wrong? Thank you very much


Solution

  • LocalStorage, sessionStorage stores strings. To change it to it original type, you have to parse it like this:

    const emailLoginLinkedin = JSON.parse(localStorage.getItem('credsForJetLeadBE'));

    After that you can use any way you want to retrieve the first key,value pair.