LocalStorage - add an object to an array of objects

I am trying to locally store an object inside an array inside an object.

If I try the following on my console, it works fine:

theObject = {} theObject.theArray = [] arrayObj = {"One":"111"} theObject.theArray.push(arrayObj) 

However, if I do what, in my opinion, is equivalent, save for saving the result in localStorage, it fails:

 localStorage.localObj = {} localStorage.localObj.localArray = [] stringArrayObj = JSON.stringify(arrayObj) localStorage.localObj.localArray.push(stringArrayObj) 

I get the following error ...

 localStorage.localObj.localArray.push(stringArrayObj) TypeError arguments: Array[2] message: "—" stack: "—" type: "non_object_property_call" __proto__: Error 

Any idea how I can make this work?

Greetings

+4
source share
2 answers

You can only store strings in localStorage. You need to JSON-encode the object, and then save the resulting string in localStorage. When the application starts, JSON decodes the value that you saved in localStorage.

 localObj = {} localObj.localArray = [] localObj.localArray.push(arrayObj) localStorage.localObj = JSON.stringify(localObj); ... localObj = JSON.parse(localStorage.localObj); 
+10
source

LocalStorage can only store key-value pairs, where the key is a string and the value is also a string. You can serialize the entire hierarchy of objects in JSON and save this as a localStorage element.

According to V8 sources (suppose you use Google Chrome, but hope this is no different for other JS engines) a TypeError with the message 'non_object_property_call' occurs than a method called undefined or a null value.

+2
source

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


All Articles