Eoin
Eoin

Reputation: 147

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.

Upvotes: 0

Views: 255

Answers (2)

Twisty
Twisty

Reputation: 30883

I would suggest something like:

var a = {},
  keys = Object.keys(localStorage);

$.each(keys, function(i, k) {
  if (k.startsWith("abc")) {
    a[k] = localStorage[k];
  }
});

console.log(a);

Test Example

var local = {
  "abc1": "yes",
  "abc2": "yes",
  "abc3": "yes",
  "uvw": "no",
  "xyz": "no"
};
var a = {},
  keys = Object.keys(local);

$.each(keys, function(i, k) {
  if (k.startsWith("abc")) {
    a[k] = local[k];
  }
});

console.log(a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This results in a new Object with just the Key Value pairs expected.

Alternate

var local = {
  "abc1": "yes",
  "abc2": "yes",
  "abc3": "yes",
  "uvw": "no",
  "xyz": "no"
};
var a = {};

$.each(local, function(k, v) {
  if (k.startsWith("abc")) {
    a[k] = v;
  }
});

console.log(a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

Barmar
Barmar

Reputation: 780787

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);

Upvotes: 1

Related Questions