I am creating a React application that you write in a recipe name and ingredients, and they will appear as a list on the page for each recipe created. I was going to use .map to create the list items, but I need an array to work with that and the localStorage is not an array(I believe anyways). Would there be a way to transport each key in the localStorage to an array?
The localStorage, each time you hit the "add recipe" button, adds a key of "recipe name" plus a number for ordering purposes. The value is the recipe itself. I just want to add the recipes to an array as well for .map.
There are multiple ways available to iterate through all keys stored in a localStorage object by using JavaScript. The above code snippet iterates over all keys stored in localStorage , and prints them on the console.
To get items from localStorage, use the getItem() method. getItem() allows you to access the data stored in the browser's localStorage object.
The removeItem() method removes the specified Storage Object item. The removeItem() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.
There are two JSON methods that can help us "store arrays" in localStorage : stringify() - It helps us convert the array into a string. parse() - It allows us to parse the string and construct a JavaScript array.
Try using Object.keys(localStorage)
. As you requested a key:
var arrayOfKeys = Object.keys(localStorage);
Easy as that! That returns an array of keys. Now, if you want the values:
var arrayOfValues = Object.values(localStorage);
It returns an array.
Note that Object.values
is experimental, so an alternative would be:
var arrayOfValues = [];
for(var i in localStorage){
if(localStorage.hasOwnProperty(i)){
arrayOfValues.push(localStorage[i]);
}
}
You can use localStorage.length
, it will give the total count of keys present in localStorage
. Iterate using this length and use localStorage.key(index)
to get the key name, like this:
for (let i = 0; i < localStorage.length; i++)
let key = localStorage.key(i);
console.log(localStorage.getItem(key));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With