I am Hack Sparrow
Captain of the Internets.

JavaScript – Get Object Size

How to get the size of an object in JavaScript

Arrays in JavaScript have a length property that gives you the number of items in an array. Objects on the other hand don't have a length property. The old method of counting the number of properties in an object involves looping through the object properties and incrementing a counter:

var my_object = {a:1, b:2, c:2};

var len = 0;
for (var o in my_object) {

console.log('Size of object: '+len);

The new and efficient method of getting the object size involves using the Object.keys() method:

console.log('Size of object: '+ Object.keys(my_object).length);

Isn't it much better? Needless to say, Object.keys() returns an array of all the properties of an object. Think of its other possible uses.

One Response to “JavaScript – Get Object Size”

  1. alejandro says:

    Gracias, thanks

Make a Comment