I am looking for quick way to get an item from the Mozilla localStorage based on partial knowledge of an unique key. I have the following structure defined as the key : value
UUID1 : "BLABLABLA": UUID2 : Value
Where the key part looks like this for example:
ca4417f4-f83b-11eb-bf45-ffc420139ccb:BLABLABLA:e1d26c40-f83b-11eb-81c0-fbcc16bf6bdb
Value is just a long string.
What would be the fastest way to find a SINGLE key from localStorage based on only one of the two UUIDs i.e. either UUID1 or UUID2, then obtain the full key string and then use
localStorage.getItem to return it's value
maybe using Object.entries(localStorage)
?
a code example would be really appreciated?
Expanding on your Object.entries() concept you can do something like:
// set a demo key/value
localStorage.setItem('foobar', 100);
const [wantedKey, wantedValue] = Object.entries(localStorage).find(([k,v])=> k.startsWith('foo'))
console.log([wantedKey, wantedValue])
The Storage
interface has a length
property telling you how many items are there, and a key
method that gives you the key for item index n. So you can loop through to find the key with a for
loop:
let key;
for (let n = 0, len = localStorage.length; n < len; ++n) {
const thisKey = localStorage.key(n);
if (thisKey.includes("BLABLABLA")) {
// found it
key = thisKey;
break;
}
}
if (key) {
const value localStorage.getItem(key);
// ...
}
Note that solutions using Object.keys
, Object.entries
, etc. won't work reliably with all storage keys — for instance, the key "length"
won't work properly even though it's just fine to use "length'
as a key with getItem
and setItem
. That's because the Storage
interface already defines a property called length
(the length of the storage list), so you can't access a stored item keyed by "length'
using localStorage.length
, you have to localStorage.getItem("length")
. Object.keys
and Object.entries
will leave out those storage entries. (Other than it appears there's a weird bug in Chrome around the "key"
key.) The above works reliably with length
, key
, and other similar keys (but really it's length
and key
that are the most problematic).
In your particular case, though, you know the key isn't length
or key
or any of the other things on Storage.prototype
, so you could create an array of keys via Object.keys
and use find
to find the key:
// Read the disclaimers above
const key = Object.keys(localStorage).find(key => key.includes("BLABLABLA"));
if (key) {
const value localStorage.getItem(key);
// ...
}
...or use Object.entries
to create an array of arrays as charlietfl shows. Just be mindful of the caveat.