Reputation: 1019
I am new at JS and before asking I searched about this question but still did not find an answer. In the LocalStorage I have only one key defined as follows:
key={
-prob1: string
-prob2: Object
-prob21:string
-prob22:string
}
How can I store in key
a given object of the same structure as prob2
let's call it obj
, is it like this ? localStorage.setItem('key.prob2', obj);
is this legal?
any ideas?thank you
Upvotes: 4
Views: 2324
Reputation: 36511
All you'd be storing with localStorage.setItem('key.prob2', obj)
is [object Object]
since it can only store strings, which probably isn't what you are looking for. I usually use a small wrapper class around localStorage
to auto-serialize/deserialize, something like:
class Storage {
static set(key, value) {
let serialized = value;
if (typeof value !== 'string') {
serialized = JSON.stringify(serialized);
}
localStorage.setItem(key, serialized);
}
static get(key) {
try {
return JSON.parse(localStorage.getItem(key));
} catch (e) {
return localStorage.getItem(key);
}
}
}
Storage.set('foo', { bar: 'baz' });
console.log(Storage.get('foo').bar);
Upvotes: 1
Reputation: 62556
You can't store Objects using localStorage
- you can only store there strings.
What you can do is convert your object to string (using JSON.stringify
) and then save it.
obj = {
a: {
b: 'c'
}
}
localStorage.setItem('myobj', JSON.stringify(obj));
console.log(localStorage.getItem('myobj'));
console.log(JSON.parse(localStorage.getItem('myobj')));
https://jsfiddle.net/or91wp56/
Upvotes: 4