How to store Javascript array in localStorage?

ยท

3 min read

Web storage object localStorage allows us to store data in the browser. The data is stored in the form of key/value pair and is shared between all windows from the same origin. Unlike the sessionStorage, the data stored in the localStorage is not cleared when we close the tab or in fact when we close the browser completely.

One important thing to note about localStorage is, it can only store strings (both the key/value pair in localStorage should be of type string). This brings us to the question - How to store arrays in localStorage?

JSON methods to rescue

There are two JSON methods that can help us in this scenario:

  • JSON.stringify() - converts an array into a string

  • JSON.parse() - parses a string and constructs an array from it

Storing an array in localStorage

To store an array in localStorage, we first need to convert it into a string.

Converting an array into a string

We can use JSON.stringify to convert an array into a string.

Let's say we have an array of users

const users = ["John", "Mark", "Peter"];

We can convert it into a string as follows:

JSON.stringify(users)

The above code will convert users array into a single string.

Store data in localStorage

Now, we can use localStorage.setItem() method to store the data in localStorage.

localStorage.setItem(key, value)

The method takes two parameters:

  • key: It specifies the name of the key
  • value: It specifies the value that we want to store

Run the below code to store users array into localStorage:

localStorage.setItem('allUsers', JSON.stringify(users))
// here 'allUsers' is the key and 'users' is the value

At this point, we should be able to open the "Application" tab in our browser's console and we should see the output as follows:

Screenshot 2022-11-01 at 2.59.09 PM.png As we can see, our users array has been added to the localStorage successfully. ๐ŸŽ‰

Retrieving data from localStorage

Okay! So after storing the data if we want to retrieve it, we can use localStorage.getItem() method.

localStorage.getItem(key)

The method only takes one parameter:

  • key: It specifies the name of the key whose value you want to get

Convert the retrieved string into an array

Once we have retrieved the data, we can convert it into an array using JSON.parse() method as follows:

const savedUsers = JSON.parse(localStorage.getItem('allUsers'));

If you have been following along, you can find the complete code below:

const users = ["John", "Mark", "Peter"];
localStorage.setItem('allUsers', JSON.stringify(users))

const savedUsers = JSON.parse(localStorage.getItem('allUsers'));

This is how we can store and retrieve array from localStorage.

Did you find this article valuable?

Support Vedansh Mehra by becoming a sponsor. Any amount is appreciated!

ย