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.
You have two problems.
startsWith()
returns a boolean, not a string.abc
, not the key.var a = {};
Object.entries(localStorage).forEach(([key, value]) => {
if (key.startsWith("abc")) {
a[key] = value;
}
});
console.log(a);