How to iterate over localStorage values

I am creating a React application that you write in the recipe name and ingredients, and they will be displayed as a list on the page for each recipe created. I was going to use .map to create list items, but I need an array to work with it, and localStorage is not an array (I believe that anyway). Will there be a way to transfer each key in localStorage to an array?

LocalStorage, every time you click the "add recipe" button, the key is added to the "recipe name" plus a number for order purposes. Value is the recipe itself. I just want to add recipes to the array as well for .map.

+4
source share
2 answers

Try to use Object.keys(localStorage). When you requested a key:

var arrayOfKeys = Object.keys(localStorage);

Simply! This returns an array of keys. Now if you want the values:

var arrayOfValues = Object.values(localStorage);

It returns an array.

Please note that this Object.valuesis experimental, so the alternative would be:

var arrayOfValues = [];
for(var i in localStorage){
    if(localStorage.hasOwnProperty(i)){
        arrayOfValues.push(localStorage[i]);
    }
}
+3
source

You can use localStorage.length, this will give the total number of keys present in localStorage. Iterate using this length and use localStorage.key(index)to get the key name, for example:

for (let i = 0; i < localStorage.length; i++)        
   let key = localStorage.key(i);
   console.log(localStorage.getItem(key));
}
0
source

Source: https://habr.com/ru/post/1664480/


All Articles