-
-
Save n0m4dz/77f08d3de1b9115e905c to your computer and use it in GitHub Desktop.
how to filter keys from localStorage with a regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// returns an array of localStorage items in key/value pairs based on a query parameter | |
// returns all localStorage items if query isn't specified | |
// query can be a string or a RegExp object | |
function findLocalItems (query) { | |
var i, results = []; | |
for (i in localStorage) { | |
if (localStorage.hasOwnProperty(i)) { | |
if (i.match(query) || (!query && typeof i === 'string')) { | |
value = JSON.parse(localStorage.getItem(i)); | |
results.push({key:i,val:value}); | |
} | |
} | |
} | |
return results; | |
} |
why do you need this line:
if (localStorage.hasOwnProperty(i)) {
?
why do you need this line:
if (localStorage.hasOwnProperty(i)) {
?
i in localStorage
iterates over all enumerable and non-Symbol properties not only over own properties
If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames() or perform a hasOwnProperty() check (propertyIsEnumerable() can also be used). Alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! I soooooooo needed to find this today. =]
I did have to remove the JSON.parse in order for it to work for my stuff.
Thanks again.