Saving and Loading Objects (or Arrays) in localStorage

November 22nd, 2012

Although localStorage is not very popular (due to size browser sizing constraints and lack of consistency), it can still be a great (and fairly cross-browser) way for storing lots of data. About 2.49-4.98MB worth depending on the browser. Check how much your browser can store by using this nifty tool by Nemikor.

Setting and getting with localStorage is dead simple. Consider this JavaScript example here:

localStorage.setItem("test", "Hello World!"); //It's saved!
var test = localStorage.getItem("test"); //Let's grab it and save it to a variable
console.log(test); //Logs "Hello World!"

Easy peasy. Except when you try something like this:

​var test = { test: "thing", test2: "thing2", test3: [0, 2, 44] }​​​​​​​;
localStorage.setItem("test", test);
var test2 = localStorage.getItem("test");
console.log(test2); //Logs "[object Object]"

Okay so, as you may notice (besides my bad variable naming), localStorage doesn’t like objects or even arrays. This is where JSON comes to the rescue. Using the ultra cool JSON.stringify function, we can turn this object into a string – since strings are things localStorage does indeed like. While it’s true that JSON functions aren’t available natively in many older browsers, such as IE7, and Firefox 3.0 – we don’t have to worry about that since we are talking about localStorage, a new HTML5 functionality which requires a new-ish browser anyways. If you still can’t use it for some reason, just take a look at JSON source and copy the function for yourself.

​var test = { test: "thing", test2: "thing2", test3: [0, 2, 44] }​​​​​​​;
localStorage.setItem("test", JSON.stringify(test));
var test2 = localStorage.getItem("test");
console.log(test2); //Logs "{"test":"thing","test2":"thing2","test3":[0,2,44]}"

Very cool! It worked. How about taking it a step further and loading them back in as variables/objects? Normally we would have to use the super duper evil eval(). Or, we could even use the window[] trick to evaluate strings as variables from the global scope. But why not take advantage of another great JSON function? JSON.parse can do the trick. Yes, it’s true that JSON.parse does in fact use eval(), it makes sure it’s clean first by only allowing JSON data.

​var test = { test: "thing", test2: "thing2", test3: [0, 2, 44] }​​​​​​​;
localStorage.setItem("test", JSON.stringify(test));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2); //var test is now re-loaded!

Thanks to Reddit user Falmarri for pointing out JSON.parse to me. Originally, I was using an example with jQuery’s .globalEval(); however, upon inspection, JSON’s .parse is technically safer, and pretty much native JavaScript in any modern browser, so I’m siding with that.

This entry was posted in Blog and tagged , , .

32 Responses to Saving and Loading Objects (or Arrays) in localStorage

July 26th, 2013
Raul says:

can i get/display a specific object? i.e. i want to display “test2: “thing2” only. if yes, how?

Reply
February 19th, 2014
A says:

I feel stupid, I have no clue hoe to do it? So I getItem(“myObj”), in there is a key “Firstname”. How do I read that key?

Reply
February 19th, 2014
Vaughn Royko says:

In that case, you would:

var myObj = JSON.parse(localStorage.getItem("myObj"));
var firstName = myObj["Firstname"];
Reply
July 26th, 2013
Raul says:

i already get it. thanks anyway. :)

Reply
August 21st, 2013
Dan says:

Very clear and easy to follow. Thanks for sharing!

Dan

Reply
October 22nd, 2013
liza says:

How can I Store an Object ?

Reply
April 16th, 2015
Ryan says:

Hey, your question’s old so you probably don’t need an answer anymore but someone might stumble across it some day.

You can store objects the same way you’d store any variable in local storage, it’s getting it back out where the problems come up.

My workaround was using a temp variable to hold the object while I parsed it and recreated it as a new object. Like this example;

var myObject = localStorage.getItem(“normal”);

var temp = JSON.parse(myObject);

myObject= new Vector3(temp.X, temp.Y, temp.Z);

Depending on your object, you may need to make sure that the values are of the right type when you make the object again but I’ve found this to work.

Reply
December 10th, 2013
Aditay Kaushal says:

can i store multiple data in one key many time
. previous data should not be delete

Reply
June 3rd, 2014
Daniel says:

No Aditay, you cannot store data under the same key name without it overwriting your previous data,

Reply
March 29th, 2014
furester says:

if the object i store has some methods i’ll lose them when i get item from storage, is there any trick so i could reassign it to the original ‘class’?

Reply
August 14th, 2014
Raviv says:

That’s Great
I’m struggling with changing a value within the inner Objects.
For example:
how would you change the value of 44
inside the object
test3: [0, 2, 44]
And by doing that i can access the local storage from any other page in my App and receive the new value.
Hope you can help

Reply
August 16th, 2014
Vaughn Royko says:

What you are looking at there is an array within an object. So for what, you would do something like object.test3[2] = 45; for example.

Reply
November 21st, 2014
rr says:

nice
thank u
it’s amazing

Reply
December 14th, 2014
Dan says:

If you where storing arrays within arrays, would you need to store all of the arrays separately or would it just be the first array storing the others?

Reply
January 22nd, 2015
Joel Tiago Pereira Fonseca says:
// ___________________________________________
//| Função para salvar os atributos inseridos |
//|___________________________________________|
function salvar_atributos(){
    var i;
    
    if(supports_html5_storage()){

        // guarda os atributos em artigos, cada artigo tem os diferentes atributos inseridos
        for(i=0; i < conjuntosnippet.length; i++) {
            localStorage.setItem('artigo' + i, JSON.stringify(conjuntosnippet[i]));
            alert('Snippet adicionado.');
        }   
    }
}

como é que faço uma função carregar os dados da função acima?

Reply
April 15th, 2015
damir says:

can i have two different objects in the same project, like a list of cars(brand,year…atributtes) and an other list of persons(name,age…atributtes)??

Reply
April 23rd, 2015
Vaughn Royko says:

Yep! There should be no issue with that.

Reply
December 6th, 2016
Vikky says:

Hello Vaughn Royko.. can you please explain how we retrive and store this array to local storage

var myarray = [{
“key1″:”1”,
“key2″:”name”
},
{
“key1″:”6”,
“key2″:”Rago”

}]

Reply
May 28th, 2015
Rafael says:

If you use AngularJS library

https://docs.angularjs.org/api/ng/function/angular.fromJson

https://docs.angularjs.org/api/ng/function/angular.toJson

Reply
September 20th, 2015
Mohd Rabi says:

Man, You’re absolutely genius

You saved my day :)

Reply
December 2nd, 2015
arbia says:

I have a form contain name and last name and a button submit. is there a way with localstorage to store all entries?

for example for the attribute name i need to store all entries :
name = x
name = y
name = y

thanks for your help

Reply
December 2nd, 2015
Vaughn Royko says:

I’m not 100% sure on what you are trying to do, but for that you would use:

localStorage.setItem("x", x);
localStorage.setItem("y", y);
localStorage.setItem("z", z);

OR

localStorage.setItem("coords", {"x": x, "y": y, "z": z});
Reply
July 4th, 2016
Pradnya says:

please suggest me how do i write -1 in array for below,

char Val_Arr[5];
char a;
{
a=0
a–;
Val_Arr[5]=a;
}

Reply
July 4th, 2016
Pradnya says:

for above mentioned Val_Arr[5] showing me 255 decimal value instead of -1

Reply
August 18th, 2016
John B says:

Hi to all,

would like to know how to save into local storage the value of “sid” from a json response i receive from a url. For ex., this is my response:
{“success” : true , “firstname” : “example” , “lastname” : “test” , “sid” : “5C9032F32394B345FC9EC526B101F40DFD0D9937B1094E9BE271D2045E8C9846}

Reply
August 18th, 2016
Vaughn Royko says:
var response = {"success" : true , "firstname" : "example" , "lastname" : "test" , "sid" : "5C9032F32394B345FC9EC526B101F40DFD0D9937B1094E9BE271D2045E8C9846"};
var sid = response.sid
localStorage.setItem("sid", sid);
Reply
September 5th, 2016
Tyler Potts says:

Is it possible to store a object inside an object and then call that second object with a specific value?

e.g.

var object = {

test: 1,

secondTest: {fries: 11, chicken: 2},

}

Reply

Leave a Reply

*

*

TOP