Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a (dictionary) object in JavaScript localStorage?

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?

like image 290
Akash Deshpande Avatar asked Dec 06 '12 12:12

Akash Deshpande


People also ask

How do I store a dictionary in localStorage?

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

Can we store JavaScript object in localStorage?

In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON. parse method.

Which JavaScript object can store data locally?

localStorage is a read-only property that returns a reference to the local storage object used to store data that is only accessible to the origin that created it.


1 Answers

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]"
like image 104
Cerbrus Avatar answered Sep 22 '22 12:09

Cerbrus