Skip to content

Instantly share code, notes, and snippets.

@blackmjck
Last active August 29, 2015 13:56
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/8809617 to your computer and use it in GitHub Desktop.
Save blackmjck/8809617 to your computer and use it in GitHub Desktop.
Simple method for calculating the length of an associative array (i.e. object). Counts the first-level child properties only.
/**
* Object Size - a simple utility function for returning the length of an associative array (i.e. object)
*
* Counts the first-level direct child properties of the object and returns the count
*
* @author Steven Wiggins
* @date 2/4/2014
* @version 0.2
*/
;(function() {
Object.prototype.size = function() {
var total = 0, prop;
// this becomes trivial if the engine supports the Object.keys() function
if( Object.keys ) {
return Object.keys( this ).length;
}
// otherwise, we do it the old-fashioned way
for( prop in this ) {
this.hasOwnProperty( prop ) && total++;
}
return total;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment