get All arrays from local storage in Angular

Viewed 1136

I have dynamically created numbered arrays in local storage:

 key:   array1     value: [{foo, bar, etc}]
 key:   array2     value: [{bar, foo, etc}]

and I want to recursively pull all of them out. doesn't have to be fancy. I can't figure out how to do it. I have:

for (array of localStorage) {
       consolelog.(JSON.parse(localStorage.getItem(array)));}

but I know this isn't right.. local storage isn't even an array. any ideas? Not sure how to handle the fact that there could be any number of them, with any number in their name.

3 Answers

You should be able to iterate through the keys with Object.keys() and call getItems() on each.

Object.keys(localStorage).forEach(data => 
{
  let item = localStorage.getItem(data);
  console.log(item); // item is the item from storage.
});

You can turn it into an array with Object.values method or Object.entries, depending on what you find more useful.

So it would be something like this:

for (array of Object.values(localStorage)) {
       console.log(array);
}

store array in your local storage as an object

localStorage.setItem("array1", ["foo", "bar", "etc"])

And get the array elements like this

for (var i = 0; i < localStorage.length; i++){
    console.log(localStorage.key(i), localStorage.getItem(localStorage.key(i)));
}
Related