5

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.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
jeff64
  • 65
  • 1
  • 4
  • Post some details, `localStorage` structure and expected array. – dfsq Dec 21 '16 at 20:12
  • `localStorage` is object, if you store anything inside as array just do `localStorage.yourArray.map` – Ilanus Dec 21 '16 at 20:13
  • 1
    Possible duplicate: http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage – Gerrit0 Dec 21 '16 at 20:18
  • Added some more details. I wouldn't say this question is the same as that one. He wanted to store an object in localStorage, while I want to basically store each recipe item into both the storage and an array. – jeff64 Dec 21 '16 at 20:20
  • EDIT: this solved my problem: https://stackoverflow.com/questions/40843773/localstorage-keeps-overwriting-my-data – Yoda Aug 26 '20 at 05:25
  • EDIT: this solved my problem: https://stackoverflow.com/questions/40843773/localstorage-keeps-overwriting-my-data – Yoda Aug 26 '20 at 05:25

2 Answers2

8

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]);
    }
}
MasterBob
  • 550
  • 1
  • 8
  • 19
4

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));
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142