Reputation: 19
I need to save all domain localStorage in variable and later set it again from variable.
I trying save localstorage with this code:
for (var i = 0, len = localStorage.length; i < len; ++i) {
objects = JSON.stringify(localStorage.getItem(localStorage.key(i)));
}
console.log(objects);
But it gives me a error. And how can i set all localstorage from variable? Something like this?
for (var i = 0, len = objects.length; i < len; i++) {
localStorage.setItem(len, objects(i);
}
Upvotes: 1
Views: 2130
Reputation: 4243
You could do something like this to set the items:
function setItem(key, value){
if (typeof value === 'object') {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
}
and something like this to retrieve it:
function getItem(key){
if (key){
try{
return JSON.parse(localStorage.getItem(key));
}
catch(e){
return localStorage.getItem(key);
}
}
}
localStorage
only save strings, numbers or booleans so if your value is an object you need to stringify it before save it, then when you retrieve it you need to parse it again to an object.
Now take this 2 functions and use them like wrappers to access the localStorage values in your loops.
[Update - Fixing Loops]
Get Data
var objects = {};
for (var i = 0, len = localStorage.length; i < len; i++) {
objects[localStorage.key(i)] = getItem(localStorage.key(i));
}
console.log(objects);
Set Data
for (var o in objects) {
setItem(o, objects[o]);
}
Upvotes: 2