Created
May 20, 2011 19:46
-
-
Save gjcourt/983637 to your computer and use it in GitHub Desktop.
Javascript Object Key Detection
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
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