11

I need to store an object like the one I the example below in localstorage. I need to be able to retrieve this object and edit it, then save it back into localStorage for next time.

var data = {lastEdit:"September", expires:"December", records:[{arrives: "12:45", departs: "12:51"}, {arrives: "13:03", departs: "13:04"}]};

I tried this but it said 'undefined':

localStorage.setItem("dataStore1", data);
var output = localStorage.getItem("dataStore1");

What can I do to fix it?

Solved

Community
  • 1
  • 1
Jamie W
  • 439
  • 3
  • 21

3 Answers3

7

Use JSON.stringify() to set JSON and JSON.parse() to convert JSON to a JavaScript object; localStorage expects a string to be set.

guest271314
  • 1
  • 15
  • 104
  • 177
4

From Using the Web Storage API:

"Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do)."

You cannot store a complex Object value in localStorage. Sorry.

Instead, you should serialize your Object as a string [hint: JSON.stringify()] and then after retrieving it parse from JSON string back to Object [hint: JSON.parse()].

Phrogz
  • 296,393
  • 112
  • 651
  • 745
3

localstorage is limited to string key/value pairs use JSON.stringify() before storing it and JSON.parse() after retrieving it.

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));
kemotoe
  • 1,730
  • 13
  • 27
  • 1
    While your answer is correct, it isn't saying anything that the other two answers that were here well before yours don't already say. – Scott Marcus Oct 18 '17 at 14:50