The localStorage only allows strings as a key/value pair. To store an array it is important to convert the array into a string using
JSON.parse() method can convert it to an array after getting it from the storage.
- Step 1: Convert the array into a string.
- Step 2: Save the string in the localStorage.
In the first step, you have to stringify the array using the
JSON.stringify() method. You just need to pass the array as its argument.
When you call this method with the
languages array, it will return the string version of it. Now we can easily store it in the localStorage.
In the Second step, I will save the converted string using the
setItem() method. As you know, localStorage keeps the data as a key/value pair. Therefore, you need to define the key for your array.
I am using
languages as the key to store
arrayString in the localStorage. I will use this key to get the value from the localStorage.
In this example, the array contains only strings. But if you need, you can use objects in the array.
Save an Array of Objects in localStorage
I have an array that contains objects as its values. To store it in the localStorage, you have to stringify the array using
Then save the string using the
setItem() method. It is the same as storing an array of strings.
getItem() method to retrieve data from the localStorage. This method takes one argument (key) and returns the value.
When you call this method, you get the value as a string. To make it an array, you have to pass the value in the
Here I am calling the
getItem() method with the
languages key. Because I used this key to store the array.
Then I will pass the value to the
Limitations of This Process
There are a few limitations that you should consider while using this process. The localStorage has a limited storage capacity. You can store between 2MB to 10MB of data.
Data from localStorage can be removed. You can't consider it as permanent storage. If a user deletes the information manually, you will lose them permanently.
You can do it by following 2 easy steps. Whenever your application needs the data, you can access those and display them on the webpage.