Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Storing and retrieving objects with LocalStorage

Posted: October 21, 2015
Written by: Saints At Play
Category: HTML5

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?

« Return to Posts

Comments

There are no comments

Posting comments after three months has been disabled.