开发者

localStorage - append an object to an array of objects

开发者 https://www.devze.com 2023-03-31 05:25 出处:网络
I\'m attempting to locally store an object within an array within an object. If I try the following in my console it works perfectly:

I'm attempting to locally store an object within an array within an object.

If I try the following in my console it works perfectly:

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

However if I do what I think is the equivalent, except storing 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

An开发者_StackOverflow中文版y idea how I can get this to work?

Cheers


You can only store strings in localStorage. You need to JSON-encode the object then store the resulting string in localStorage. When your application starts up, JSON-decode the value you saved in localStorage.

localObj = {}
localObj.localArray = []
localObj.localArray.push(arrayObj)

localStorage.localObj = JSON.stringify(localObj);
...
localObj = JSON.parse(localStorage.localObj);


LocalStorage can store only key-value pairs where key is string and value is string too. You can serialize your whole object hierarchy into JSON and save that as localStorage item.

According to V8 sources (I assume you using Google Chrome but hope this isn't different for other JS engines) TypeError with message 'non_object_property_call' occurs than method called on undefined or null value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号