14

I have a very simple dictionary .

var meta = {'foo':'1','moo':'2'}

I want to store this in the local storage and retrieve it.

 window.localStorage.setItem("meta", meta);
 var meta1 = window.localStorage.getItem("meta");
 alert(meta1['foo']);

The above does not work. How can I do it?

Cerbrus
  • 65,559
  • 18
  • 128
  • 140
Akash Deshpande
  • 2,433
  • 9
  • 39
  • 79
  • Possible duplicate of [Storing Objects in HTML5 localStorage](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – Michal Mau Aug 05 '16 at 08:34

1 Answers1

36

localStorage converts it's input to strings, so you will have to convert your objects to JSON strings, and back:

window.localStorage.setItem("meta", JSON.stringify(meta));
var meta1 = JSON.parse(window.localStorage.getItem("meta"));
alert(meta1['foo']);

The reason your code didn't work is because setting a object in localStorage sets it's value to "[object Object]" (object.toString() returns "[object Object]"):

window.localStorage.setItem("objectInput", {some:"object"});
var objectOutput = window.localStorage.getItem("objectInput");
alert(objectOutput);
// This returns "[object Object]"
Cerbrus
  • 65,559
  • 18
  • 128
  • 140