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.
1. Store array in localStorage
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
.
// ONLINE-RUNNER:browser;
var items = ['item-1', 'item-2', 'item-3'];
window.localStorage.setItem('storedItems', JSON.stringify(items));
2. Get array from localStorage
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.
// ONLINE-RUNNER:browser;
var items = JSON.parse(window.localStorage.getItem('storedItems'));
console.log(items); // Output: ['item-1', 'item-2', 'item-3']