Skip to content

Instantly share code, notes, and snippets.

@jorenvo
Created March 15, 2016 19:30
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 jorenvo/657f7ef3ed8495f09b03 to your computer and use it in GitHub Desktop.
Save jorenvo/657f7ef3ed8495f09b03 to your computer and use it in GitHub Desktop.
// requires a little bit of extra work to make it pretty, but works
// allows to recursively search js objects or arrays for a property name
// useful when dealing with big js objects you're unfamiliar with
var visited = [];
function is_type (thing, type) {
var to_string_type = '[object ' + type + ']';
return Object.prototype.toString.call(thing) === to_string_type;
}
function rgrep (arr, key, path_to_match) {
// console.log('call with ' + arr);
var was_array = true;
path_to_match = path_to_match || "";
visited.push(arr);
if (! is_type(arr, 'Array')) {
was_array = false;
arr = [arr];
}
arr.forEach(function (el, index) {
for (var prop_name in el) {
var prop_val = undefined;
try {
prop_val = el[prop_name];
} catch (e) {}
// substring match
// if (prop_name.match(new RegExp(key, 'i'))) {
if (prop_name === key) {
if (was_array) {
console.log(path_to_match + "[" + index + "]");
} else {
console.log(path_to_match);
}
console.log('FOUND MATCH ' + key);
}
// console.log(prop + ' ' + el[prop]);
if ((is_type(prop_val, 'Array') || is_type(prop_val, 'Object')) && visited.indexOf(prop_val) === -1) {
var new_path = "" + path_to_match;
if (was_array) {
new_path += "[" + index + "]";
}
new_path += "." + prop_name;
rgrep(prop_val, key, new_path);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment