PPNFilms
PPNFilms

Reputation: 65

Get part of a value from localStorage - Angular

so i have an interface callled UserData that contains 4 things: name, shortname, groups & profile.

Although, i just wanna get a portion of UserData, not the whole thing, i just want the profile value; he's a screenshot of how's my key/value relation into localStorage:

enter image description here

I'm getting UserData like this: var busca = localStorage.getItem('userData');

But this is going to get the whole thing, i just want the profile 'RENDA_FIXA'

I can't share the whole code here due to security matters, it's from work.

Well, someone knows how to pick a partial value of this UserData key, and not the whole value? Would something like: "var busca = localStorage.getItem('userData.profile');" works?

Appreciate it, best regards.

Upvotes: 0

Views: 510

Answers (3)

Barremian
Barremian

Reputation: 31145

From the docs:

The keys and the values are always in the UTF-16 DOMString format, which uses two bytes per character. (As with objects, integer keys are automatically converted to strings.)

So partial retrieval isn't possible from the Storage interface. You need to retrieve the complete value (string) first, parse it with JSON.parse() and access the required property.

Upvotes: 1

wentjun
wentjun

Reputation: 42606

You will need to use JSON.parse to convert it into an object first, before destructuring it:

const { profile } = JSON.parse(localStorage.getItem('userData'))

Upvotes: 1

Aakash Garg
Aakash Garg

Reputation: 10979

while assigning you can decide which property to assign because localstorage can only access on the basis of key i.e. userData. For eg:-

JSON.parse(localStorage.getItem('userData'))['profile']

Upvotes: 1

Related Questions