Sometimes, we want to get the keys of the items that we stored in our browser’s local storage in our web app.
In this article, we’ll look at how to get the keys of the items stored in local storage with JavaScript.
Use the Object.entries Method
We can use the Object.entries
method to get the keys and values of the items stored in local storage.
For instance, we can write:
localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const entries = Object.entries(localStorage)
console.log(entries)
Then entries
is:
[
[
"foo",
"1"
],
[
"bar",
"2"
]
]
since Object.entries
returns an array of key-value pair arrays in the localStorage
object.
We use localStorage.setItem
with the key and value of the item we want to store as arguments respectively.
Use the Object.keys Method
Also, we can use the Object.keys
method to get the keys of the items that are stored in local storage.
For instance, we can write:
localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const keys = Object.keys(localStorage)
console.log(keys)
Then keys
is [“foo”, “bar”]
.
Use the localStorage.key Method
Another way to get all the keys of the items stored in local storage is to use the localStorage.key
method.
We can use it along with the localStorage.length
property to create an array to populate the keys with.
localStorage.length
has the number of items stored in local storage.
To use them, we can write:
localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const keys = [...Array(localStorage.length)].map((o, i) => {
return localStorage.key(i);
})
console.log(keys)
We spread the empty array with length localStorage.length
, spread that into a new array, then call map
with a callback to return the key that we get by calling localStorage.key
with the i
index.
As a result, keys
is also [“foo”, “bar”]
.
Conclusion
There’re several ways we can use the get the items stored in local storage with JavaScript.