Skip to content

Instantly share code, notes, and snippets.

@clochix
Last active November 29, 2018 03:43
Show Gist options
  • Save clochix/3958723 to your computer and use it in GitHub Desktop.
Save clochix/3958723 to your computer and use it in GitHub Desktop.
Recursive search in JavaScript
/**
* Search into object where for value what
*
* @param {Object} where
* @param {String|Regexp} what
*
* @return display matching keys
*
* Sample:
* include('deepSearch');
* deepSearch(window, 'toto');
* deepSearch(window, /size/); // All objects whose key or value match /size/
*/
function deepSearch(where, what) {
var res = [];
if (Object.prototype.toString.call(what).match(/^\[object\s(.*)\]$/)[1].toLowerCase() === "regexp") {
function match(obj, key) {
return what.test(obj[key]) || what.test(key);
}
} else {
function match(obj, key) {
return obj[key] == what;
}
}
function innerSearch(o, v) {
var search = function search(obj, pattern, prefix) {
prefix = prefix || '';
return function(a) {
if (typeof obj[a] === "object" && obj[a] !== null) {
Object.keys(obj[a]).forEach(search(obj[a], pattern, /\d+/.test(a) ? prefix + '[' + a + ']' : (prefix !== '' ? prefix + '.' : '') + a));
} else {
if (match(obj, a)) {
res.push(prefix + '.' + a + ' = ' + obj[a]);
}
}
};
}
o = JSON.decycle(o);
Object.keys(o).forEach(search(o, v));
console.log(res.join("\n"));
}
if (typeof JSON.decycle !== 'function') {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://raw.github.com/douglascrockford/JSON-js/master/cycle.js';
document.getElementsByTagName('head')[0].appendChild(script);
var waitFct = function() {
if (typeof JSON.decycle !== 'function') {
setTimeout(waitFct, 500);
} else {
innerSearch(where, what);
}
};
waitFct();
} else {
innerSearch(where, what);
}
}
@Camusensei
Copy link

Hi. Your code does not work for the window object... Check out my (rudimentary) version that works: http://thican.net/~camusensei/js.html
(sorry for the unclean code ^^)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment