Waleed Naveed
Waleed Naveed

Reputation: 2381

How to store object in localStorage

I have the following code:

localStorage.setItem("ActiveDataOfpModel", iHandle.find("ul li.pModel.active"));

When i check "ActiveDataOfpModel" value in console i get "[object Object]". How can i store the actual object in "ActiveDataOfpModel" and retrieve its properties. i.e. i want to do the following:

var value = localStorage.getItem("ActiveDataOfpModel").attr("data-id")

i did try

var value = JSON.parse(localStorage.getItem("ActiveDataOfpModel")).attr("data-id")

but its not working

Upvotes: 3

Views: 3938

Answers (2)

ErShakirAnsari
ErShakirAnsari

Reputation: 652

Try this:
Convert it to String before saving to LocalStorage

localStorage.setItem('key', JSON.stringify(data));

Convert back to JSON object, when reading from LocalStorage

data = JSON.parse(localStorage.getItem('key');

Upvotes: 3

Quentin
Quentin

Reputation: 943569

You can only store strings in local storage.

You can encode simple objects as JSON (they must contain only JSON data types such as objects, numbers, and strings) as a string using JSON.stringify(someObject).

var value = JSON.parse(localStorage

… and that is how to convert the JSON back to an object afterwards.


Your code iHandle.find("ul li.pModel.active") implies you are not dealing with a simple object though. That is something I would expect to return a DOM element or something akin to it.

You would need to extract the data you care about from it, store that in an object, store that in the JSON and then the localstorage, and write more code to convert the simple data back in to the full object when you pull the data out afterwards.

Upvotes: 3

Related Questions