Skip to content

Instantly share code, notes, and snippets.

@gjcourt
Created May 20, 2011 19:46
Show Gist options
  • Save gjcourt/983637 to your computer and use it in GitHub Desktop.
Save gjcourt/983637 to your computer and use it in GitHub Desktop.
Javascript Object Key Detection
function detect(obj, attr, exact) {
var results = [],
re = new RegExp(attr, 'i');
// helper function for the recursion
function detectHelper(obj, attr, exact, path, results) {
for (var a in obj) {
// sanity check
if (!obj.hasOwnProperty(a))
continue;
// check the current key
if (!exact && re.test(a) || (exact && a == attr))
results.push(path + a);
// recusrively check values
if (obj[a] && obj[a].constructor.toString().indexOf('Object') != -1)
detectHelper(obj[a], attr, exact, path + a + '/', results);
}
}
detectHelper(obj, attr, exact, '/', results);
try {
for (var i = 0; i < results.length; ++i)
console.log(results[i]);
} catch(e) { /* do nothing */}
// return results;
}
Object.prototype.detect = function(attr, exact) {
var results = [],
re = new RegExp(attr, 'i');
// helper function for the recursion
function detectHelper(obj, attr, exact, path, results) {
for (a in obj) {
// sanity check
if (!obj.hasOwnProperty(a))
continue;
// check the current key
if (!exact && re.test(a) || (exact && a == attr))
results.push(path + a);
// recusrively check values
if (obj[a] && obj[a].constructor.toString().indexOf('Object') != -1)
detectHelper(obj[a], attr, exact, path + a + '/', results);
}
}
detectHelper(this, attr, exact, '/', results);
try {
for (var i = 0; i < results.length; ++i)
console.log(results[i]);
} catch(e) { /* do nothing */}
// return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment