0

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.

Eoin
  • 147
  • 1
  • 2
  • 16

2 Answers2

1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I didn't get what i wanted. I can see only [object Object]. – Eoin Aug 28 '20 at 15:14
  • I don't think any of my code would cause that. That will happen if you tried to store objects in local storage without converting them to JSON first. – Barmar Aug 28 '20 at 15:30
  • See https://stackoverflow.com/questions/4750225/what-does-object-object-mean – Barmar Aug 28 '20 at 15:31
0

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>
Twisty
  • 30,304
  • 2
  • 26
  • 45