Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through localStorage values

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.

like image 732
jeff64 Avatar asked Dec 21 '16 20:12

jeff64


People also ask

Can you loop through local storage?

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.

How do I get data from localStorage?

To get items from localStorage, use the getItem() method. getItem() allows you to access the data stored in the browser's localStorage object.

What is localStorage removeItem?

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.

Can we set array in localStorage?

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.


Video Answer


2 Answers

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]);
    }
}
like image 92
MasterBob Avatar answered Oct 20 '22 23:10

MasterBob


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));
}
like image 4
Mayank Shukla Avatar answered Oct 20 '22 23:10

Mayank Shukla