How to put Objects on HTML5 sessionStorage/localStorage

HTML5 sessionStorage and localStorage only allows you to store strings, but sometimes it’s very convenient to add more complex values like arrays and objects. Here a simple way to do that:

var array = [];
array.push('a');
array.push('a');
array.push('c');
 
// Put object on sessionStorage
sessionStorage.setItem('key', JSON.stringfy(array));
 
// Get object from sessionStorage
var object = JSON.parse(sessionStorage.getItem('key'));

As you can see in the example I’ve just converted my array to a string before storing it in the sessionStorage, then I converted it back to an array when I retrieved it from the sessionStorage. This was a very simple workaraound, hope it helps!

Recommended for you

How to Load a JSON file in Javascript In this post I'm going to give you a very simple example of how to read a JSON file and display the data on the page. I'll be using jQuery in this example, so if you don't have it on your project don't forget to add the script. So let's get started, first we need a JSON, you probably already have...
AngularJS Tutorial: ui-router example Since ui-router is one of the most useful features that angular can provide I decided to write this tutorial just to show how to use it, I'm going to create a very simple application that illustrates how to create templates using ui-router states. After donwloading angular.min.js and angular-ui-r...
Tutorial: Creating Reusable Code with AngularJS Directives I know this may not be new for most of you, but when it comes to directives a lot of people still get really confused, so let's start by looking at its definition, according to AngularJS documentacion: Directives are markers on a DOM element (such as an attribute, element name, comment or CSS...
Tutorial: Basic DataTable (sorting, filtering and pagination) with AngularJS and ng-Table In this tutorial I’m going to show you how to create a simple DataTable with some basic features, which are sorting, filtering and pagination. To accomplish this I’m going to use AngularJS with the module ng-Table. First we need to create our project, after doing it, no matter your folder structu...

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>