20

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?

0

1 Answer 1

45

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]"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.