Search code examples
jquerylocal-storagekeyvaluepair

Jquery to retrieve multiple keys with same starting pattern from LocalStorage


Consider I'm storing 5 datas using localStorage.setItem():

{"abc1":"yes", "abc2":"yes", "abc3":"yes", "uvw":"no", "xyz":"no"}

For retrieving we can use localStorage.getItem(). But here I need to retrieve all the key value pairs whose key name starts with the string "abc" i.e. to retrieve keys "abc1", "abc2" and "abc3".

This is what i tried :

var a = {}, 
keys = Object.keys(localStorage),
l = keys.length;
        
while (l--) { 
  a[keys[l]] = localStorage.getItem(keys[l]);
  if(a[keys[l]].startsWith('abc') == "true") {
    alert(a[keys[l]]);
  }
}

 

Please help me.


Solution

  • You have two problems.

    1. startsWith() returns a boolean, not a string.
    2. You're checking whether the value begins with abc, not the key.
    var a = {};
    Object.entries(localStorage).forEach(([key, value]) => {
      if (key.startsWith("abc")) {
        a[key] = value;
      }
    });
    console.log(a);