Reputation: 65
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:
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
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
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
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