JavaScript

How to save an object in localStorage

April 21, 2022

How to save an object in localStorage

In this article we will learn how to save an object in localStorage – also how we can assign it to a variable retrieving it from localStorage

How to save an object in localStorage thumb

Hey you programmer, ok? Let’s learn more about JavaScript and localStorage!

What is localStorage and sessionStorage?

First it is good to understand what is localStorage, and also sessionStorage

The localStorage allows us to access an object called Storage, we can store data in it, and that does not expire

SessionStorage, which is a similar service, has its data expired after a while, but it works the same as localStorage

How to save objects to localStorage

We cannot save objects directly to localStorage as it is a service which is limited to key and value pairs

So what can be done to avoid this limitation?

We can transform the object into a string and when we rescue it transform into an object again

See an example:

let person = {name: 'Matheus', age: 29}

// save value
localStorage.setItem('pessoa', JSON.stringify(person));

// get value
let personString = localStorage.getItem('person');

let personObj = JSON.parse(personString);

console.log(personObj.name); // Matheus

With the JSON.stringify instruction we were able to transform the object into a string, without losing its formatting, we use the setItem method to save it in localStorage

Then to retrieve this value we will need the getItem method

And finally, to convert the string into an object again, we use JSON.parse

See that in the last line we are again using the object with its name property in a normal way

Conclusion

In this article we learned how to save an object in localStorage

First we need to turn it into a string, as localStorage is a service that limits your data to key and value pairs

When rescuing the object in string format, we can convert it to object again with JSON.parse method

And that’s it, we can use the object normally!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x