Grow your CSS skills. Land your dream job.

Last updated on:

Get Object Size

As in, the number of keys.

function objectSize(the_object) {
  /* function to validate the existence of each key in the object to get the number of valid keys. */
  var object_size = 0;
  for (key in the_object){
    if (the_object.hasOwnProperty(key)) {
      object_size++;
    }
  }
  return object_size;
}

Usage

// Arbitrary object
var something = {
  dog: "cat",
  cat: "dog"
}

console.log(objectSize(something));
// Logs: 2

Comments

  1. code200
    Permalink to comment#

    Be sure to add var in front of key in your loop:

    for (var key in the_object){

    so the variable key goes out of scope with the function.

    Most recent browsers support this shorter version:
    Object.keys(something).length;
    
  2. Just ran across this post while debugging code for IE. IE versions before 9 seem to have a problem with Object.keys and .hasOwnProperty used directly on an object. So a more sophisticated replacement is necessary, which can be found here:

    http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation

    Hope this helps.

  3. Sam Purcell
    Permalink to comment#

    I like this Chris, but it seems more correct to add it to the Object prototype. IE

    Object.prototype.size = function() {
    var size = 0
    // your code, but using "this"

    return size;
    }
    Called with something.size()

    From what I understand, adding a new function to the object prototype should not be a problem.

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".