Storing and retrieving objects with LocalStorage

October 21, 2015, 10:20 pm
Author: James Griffiths

The HTML5 Web Storage API provides developers with greater latitude for front-end storage compared to that of cookies, particularly with the localStorage property, making this an excellent choice for managing data within web and mobile applications.

Aside from browser support one issue with using this API is that data saved within localStorage can be of only 2 types: strings or integers.

So where does this leave us with other data types such as Objects and Arrays?

JSON is your friend

As the localStorage object stores data in the form of key/value pairs like this:

localStorage.setItem("key", "value");

We can take an associative array such as:

var films = [
             {
              'id': 1,
              'title':'John Wick',
              'Genre':'Action'
             },
             {
              'id': 2,
              'title':'Taken 3',
              'Genre':'Action'
             },
             {
              'id': 3,
              'title':'The Guard',
              'Genre':'Comedy'
             }
            ];

And, using the JSON stringify method, convert this object into a data format that the API can easily work with which is - yes, you guessed it - a string:

localStorage.setItem("films", JSON.stringify(films));

When it comes to retrieving this value and converting it back into a JavaScript object we use the JSON parse method:

var movies = localStorage.getItem("films");
movies     = JSON.parse(movies);

Which, if we were to use the dir method of the console object on the parsed data like so:

console.dir(movies);

Would display output akin to the following structure:

0: Object
  Genre: "Action"
  id: 1
  title: "John Wick"
1: Object
  Genre: "Action"
  id: 2
  title: "Taken 3"
2: Object
  Genre: "Comedy"
  id: 3
  title: "The Guard"

Nice and easy, huh?

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.