2

I am running an old version of Angular - I have an object within my localStorage and I am trying to retrieve a single item from the object (rather than the whole the thing..)

var email = localStorage.user;

However the output of the localStorage.user variable is much longer (see below)- how would I retrieve the email address in this case 'bob@abc.com'?

{"firstname":"Bob","lastname":"Dole","id":"2000001999","accountId":"15","email":"bob@abc.com","instances":[{"name":"Test"}]}"
Zabs
  • 13,852
  • 45
  • 173
  • 297

3 Answers3

2

LocalStorage values are always stored as strings. In order to refer to the email in the object, we need to convert it to a JSON. We can do that by parsing the string using JSON.parse() method like below :

var email = JSON.parse(localstorage.user).email
Supradeep
  • 3,246
  • 1
  • 14
  • 28
2

You have Json structure not JS object, so parse it 1st

var email = JSON.parse(localStorage.user).email;
Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
0

Using html5 local storage we can store data, add expire time by using cookies and sessions. https://stackoverflow.com/a/41385990/6554634 go through that, gives a lot of explanation

Community
  • 1
  • 1
Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62