Last active
January 3, 2016 14:29
-
-
Save blackmjck/8476728 to your computer and use it in GitHub Desktop.
Simple method for returning object keys as an (optionally multidimensional) array, a la popular back-end languages. Uses the underlying Object.keys(obj) method where possible.
This file contains 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
/** | |
* Keyring - a quick polyfilled solution for getting object keys as an (optionally multidimensional) array. | |
* | |
* Accepts an optional argument to recurse into and retrieve the keys of child objects as objects in the | |
* { obj: KEYNAME, keys: [KEYS] } format. | |
* | |
* @author Steven Wiggins | |
* @date 1/17/2014 | |
* @version 0.2.2 | |
**/ | |
;(function(){ | |
Object.prototype.keyring = function( deep ) { | |
var deep = ( typeof deep === 'boolean' ) ? deep : false, | |
result = [], | |
n = 0, | |
key; | |
if( Object.keys ) { | |
result = Object.keys( this ); | |
} else { | |
for( key in this ) { | |
result.push( key ); | |
} | |
} | |
if( deep ) { | |
n = result.length; | |
while( n-- ) { | |
key = result[ n ]; | |
if( typeof this[ key ] === 'object' ) { | |
result[ n ] = { | |
obj : key, | |
keys : this[ key ].keyring( true ) | |
}; | |
} | |
} | |
} | |
return result; | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment