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

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...
How to use ES6 (Very Simple Example) Compiling Javascript ES6 Code with Babel This will be a very simple tutorial on how to use, the new and far more sophisticated version of Javascript, the ES6 (or ES2015 if you prefer). Much people say ES6 is the future of Javascript, but as everybody knows, our browsers cannot run code in this f...
Tutorial: Creating Node.js modules In this short tutorial I'm going to explain how you can create your own modules in Node.js, as everyone knows we cannot keep our entire code in only one js file, as your application grows it'll be almost impossible for you to maintain your code, for this reason it's essential that we separate ou...
Node.js: How to make POST Requests with JSON data In this post I'm going to show you how to work with POST requests, I'll give you an example as simple as possible. First I'll create the Nodejs app to receive the requests, then I'll show you how to make the requests from the frontend. We're going to be using Expressjs, it's a very popular npm pa...

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>