Skip to content

Instantly share code, notes, and snippets.

@ndvbd
Created May 4, 2018 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndvbd/86cd48490b98a27b9a1e5636bba614e2 to your computer and use it in GitHub Desktop.
Save ndvbd/86cd48490b98a27b9a1e5636bba614e2 to your computer and use it in GitHub Desktop.
Search everything in a javascript object
// Invoke with prefixpath = '', stackdepth = 0, maxdepth = 5
function searchObject(obj, textToSearch, prefixpath, stackdepth, maxdepth){
if (stackdepth >= maxdepth) return;
for (var key in obj) {
try {
if (obj.hasOwnProperty(key)) {
if (key.includes(textToSearch)) {
console.log(prefixpath + "/" + key + " key is: " + (typeof key) + " " + key);
}
if (typeof obj[key] == 'object') {
searchObject(obj[key], textToSearch, prefixpath + '/' + key, stackdepth + 1, maxdepth);
} else if (typeof obj[key] == 'string') {
if (obj[key].includes(textToSearch)) {
console.log(prefixpath + "/" + key + " -> " + (typeof obj[key]) + " " + obj[key]);
}
} else if (typeof obj[key] == 'number') {
if (obj[key].toString().includes(textToSearch)) {
console.log(prefixpath + "/" + key + " -> " + (typeof obj[key]) + " " + obj[key]);
}
} else if (typeof obj[key] == 'boolean') {
// do nothing with boolean yet
} else if (typeof obj[key] == 'function') {
// do nothing with functions yet
} else if (typeof obj[key] == 'undefined') {
// do nothing with functions yet
} else if (typeof obj[key] == 'symbol') {
// what is symbol?
} else {
console.log(prefixpath + "/" + ' Unhandled type: ' + typeof obj[key]);
}
}
} catch (e ) {
if (e instanceof TypeError) {
// can happen its okay: VM1443:5 Uncaught TypeError: obj.hasOwnProperty is not a function
} else {
throw e;
}
// can happen
}
}
} // EOF searchObject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment