Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  194] [ 2]  / answers: 1 / hits: 18456  / 12 Years ago, thu, december 6, 2012, 12:00:00

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?


More From » json

 Answers
10

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]

[#81582] Wednesday, December 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
4 Years ago
kevonmoisesf questions
Sat, Jan 23, 21, 00:00, 3 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
;