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,968
  • 6
  • 32
  • 49

3 Answers3

2
Object.getOwnPropertyNames(localStorage)
      .filter(key => localStorage[key].startsWith("e"))
      .map(key => localStorage[key]);
Mike Ezzati
  • 2,968
  • 1
  • 23
  • 34
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
  • 10,052
  • 15
  • 33
  • 44
SF..MJ
  • 862
  • 8
  • 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,516
  • 15
  • 23