Store a JavaScript object in localStorage and sessionStorage

For training and consulting, write to us at info@xrmforyou.com

I have written a blog recently on sessionStorage and localStorage. However few questions I received on that blog is how can we store Javascript objects in sessionStorage and localStorage. Storing simple string and integer values are fine but what if you want to store a JavaScript object and get it back.
Let’s try this simple code. Here I am declaring this JavaScript object and uploading in session storage.


image


Well once you execute this code, it shall work just fine. But the problem is while getting this value back. Let’s see what you get when you try to get the value of this back.


image


You get the string representation of the object. And not the actual object back.
Then how do you upload. Well the way is to convert your object into JSON and set the value in sessionStorage or localStorage.


image


And when you get the value back, you can get it using JSON.parse.


image


And that’s it. Piece of cake!


Hope this helps!
Debajit Dutta
(Microsoft MVP)


Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe to get the latest posts sent to your email.

Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading