Storing objects in localStorage
Storing objects in localStorage
In the past week I’ve been looking into the different flavors of client side
storage and how they differ. localStorage is one of the solutions offered which has
the advantage of being covered by a W3C spec but only saves key/value pairs so if you
want to store an object you’re out of luck, right? Wrong.
First a little about local storage…
The formula for adding to localStorage is pretty straight forward.
localStorage.setItem('key','value')
…saves a key/value pair while…
localStorage.getItem('key')
retrieves a set key/value pair. You can also remove an item by calling..
localStorage.removeItem('key')
or remove all items in your site’s storage
with…
localStorage.clear().
Now back to storing objects. Take the following petNames object below as an example:
var petNames = { dog: 'TiVo',
cat: 'Flickr',
fish: 'Frank'
};
If you store petNames directly into local storage like this:
localStorage.setItem('petNames', petNames);
and you access the values like this:
var storedPetNames = localStorage.getItem('petNames');
console.log(storedPetNames);
you get this:
[object Object]
That bites, but there is a way to get around this by storing the petNames object as a string.
We can accomplish this by bringing in our old pals JSON.stringify and JSON.parse.
Here’s how to do it:
localStorage.setItem('petNames', JSON.stringify(petNames));
var storedPetNames = JSON.parse(localStorage.getItem('petNames'));
console.log(storedPetNames.cat);
And there you have it - A way to save and retrieve an object in localStorage.
Up next I’ll look into the basics of indexedDB.