Why doesn't localStorage accept my object?

I need to save an object like the one below in localstorage . I need to get this object and edit it, and then save it back to localstorage 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 he said 'undefined':

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

What can I do to fix this?

solvable

+5
source share
3 answers

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

+8
source

From Using the Web Storage API :

"Storage objects are simple storages of key values, similar to objects, but they remain unchanged when loading pages. Keys and values ​​are always strings (note that whole keys will be automatically converted to strings, just like objects).

Cannot store complex Object value in localStorage. Unfortunately.

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

+4
source

localstorage limited to pairs of string keys / values, use JSON.stringify() before saving and JSON.parse() after retrieving.

 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)); 
+3
source

Source: https://habr.com/ru/post/1272725/


All Articles