EN
JavaScript - store array in localStorage
0 points
In this article, we would like to show you how to store an array in localStorage using JavaScript.
Since localStorage
only supports strings, arrays must be converted to a string format.
In this example, we use JSON.stringify()
method to convert array to string and then setItem()
method to save the items array in the localStorage
.
xxxxxxxxxx
1
var items = ['item-1', 'item-2', 'item-3'];
2
3
window.localStorage.setItem('storedItems', JSON.stringify(items));
When we want to get the array from the localStorage
, we need to convert it back to the array type (since we can only get a string from the localStorage
).
In this example, we use getItem()
method to get items
array from the localStorage and JSON.parse()
to convert the string back to the array type.
xxxxxxxxxx
1
var items = JSON.parse(window.localStorage.getItem('storedItems'));
2
3
console.log(items); // Output: ['item-1', 'item-2', 'item-3']