Skip to content

Instantly share code, notes, and snippets.

@blackmjck
Last active January 3, 2016 14:29
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 blackmjck/8476728 to your computer and use it in GitHub Desktop.
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.
/**
* 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