PDA

View Full Version : Any way to store an OBJECT in LocalStorage?



Krupski
Mar 21st, 2011, 07:55 PM
Hi all,

I've been experimenting with Local Storage. I can do things like this just fine:

localStorage.setItem('variable_name', variable_value); // write a value

var variable_value = localStorage.getItem('variable_name'); // read a value

localStorage.removeItem('variable_name'); // delete a value


But if I do this:

var object = { width : w, height : h };

...then place it in local storage, reading it back gives me a TEXT STRING that says "[Object object]" and not the actual object.

I would like to be able to store multiple values in one object, but it doesn't seem to work.

I also tried to store a variable obtained with "document.getElementById" and when read back it just says [HTMLDivElement] (something like that) instead of the actual element.

Am I doing something wrong, or does local storage not support objects?

(btw, tested on FF 3.6).

Thanks!

-- Roger

DaveyErwin
Mar 21st, 2011, 08:58 PM
The name of the var that holds the object is meaningless without
its context so you must serialize the object and store the serialization.
Then when you retrieve it populate a new object with the
serialized data.

I have probably missunderstood the question so my reply
may not be applicable.

Sorry.

devnull69
Mar 21st, 2011, 09:01 PM
Modern browsers can use JSON.stringify to serialize and JSON.parse to deserialize. I don't know about IE though



var objectString = JSON.stringify(myObject);
...
// store objectString in localStorage
...
var myObjectRetrieved = JSON.parse(objectString);

Old Pedant
Mar 21st, 2011, 09:02 PM
Yep, you'll have to create serialization/deserialization methods for objects you want to store like that.

Understand: Local storage is, for all intents and purposes, a *file*. And files don't know what a JavaScript object is.

More than that, a JavaScript object is not some nice neat package of a single block of memory. Any references in the object (non-primitives) will, of necessity, be pointing to other objects.

You might start here:
http://www.google.com/search?q=javascript+serialize+object

EDIT: Sheesh, beaten by seconds. <grin/>

Krupski
Mar 21st, 2011, 11:11 PM
Thanks all... I got it! That was easy! :D

--Roger


OK, I found something out - don't know if I'm making a mistake or what...

I did this:

var e = document.getElementById('logo').parentNode; // a valid node on my board
alert(e.id);

...correctly returns the string "site-description" (which is the ID of the DIV element).

Now, if I encode it...

var x = JSON.stringify(e);
alert(x);

It returns the string {}

Then if I decode it...

var y = JSON.parse(x);
alert(y);

It shows "[object Object]" (makes sense so far)

But is it real?

alert(y.id); (should show "site-description")

But it return "undefined". :(

Why?



(again, this is in FF 3.6.15 - Linux).