Using HTML5 localStorage to store objects and arrays

Did you know that you can use localStorage to store JSON objects and arrays? Many times you will need quick access to these items and you shouldn’t have to duplicate…

Did you know that you can use localStorage to store JSON objects and arrays? Many times you will need quick access to these items and you shouldn’t have to duplicate calls with AJAX or store them in volatile sessions.

Using localStorage, you can store key/value pairs as strings so in order to store objects and arrays, you have to store as string and then parse it before use:

Objects

// This could also be a remote json file through $.ajax or $.getJSON
var myObject = {field1 : 'foo' , field2 : 'bar'};
var myObjectArray - ["item1","Item2"];
localStorage.setItem("myObjectName",JSON.stringify(myObject));
var usableObject  = JSON.parse(localStorage.getItem("myObjectName"));

Arrays

var items = ["Item1", "Item2", "Item3"];
localStorage["itemArray"] = JSON.stringify(items);
var storedItems = JSON.parse(localStorage["itemArray"]);

The application of this would allow you to store objects and arrays for use over and over with a huge increase in speed and stability in your application.