0

Is there a way to retrieve all data in local storage in one single call?

Without using specific key (getItem('key').

What I like is to load all data and then check them for a certain prefix.

cluster1
  • 4,216
  • 5
  • 26
  • 43

3 Answers3

2
Object.getOwnPropertyNames(localStorage)
      .filter(key => localStorage[key].startsWith("e"))
      .map(key => localStorage[key]);
Mike Ezzati
  • 2,608
  • 1
  • 22
  • 32
1

This will give you all the keys

var local = localStorage;
for (var key in local) {
  console.log(key);
}

Also you can use Object.keys().

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

console.log(Object.keys(localStorage))
Narendra Jadhav
  • 9,619
  • 15
  • 29
  • 41
useless'MJ
  • 797
  • 6
  • 19
1

If you want to get certain items that staty with your custom prefix, you can first at all retrieve all localStorage keys, filter it, and then retrieve the data:

ES5

var prefix = 'your-prefix:'

var filteredStorage = Object.keys(localStorage)
  .filter(function(key) {
    return key.startsWith(prefix)
  })
  .map(function(key){
    return localStorage.getItem(key)
  })

ES2015

let prefix = 'your-prefix:'  
let filteredStorage = Object.keys(localStorage)
  .filter(key => key.startsWith(prefix))
  .map(key => localStorage.getItem(key))
dloeda
  • 1,496
  • 15
  • 23