I am Hack Sparrow
Captain of the Internets.

JavaScript: get the number of properties in an object WITHOUT LOOPING

How to get the number of properties in a JavaScript object without looping

Unlike arrays, JavaScript objects do not a have a length property which gives you the number of properties / items in an object. The most common way of getting the number of properties is to loop through the object - not pretty, resource intensive.

This had been a long known problem JavaScript developers have been facing for a long time. All modern and superior browsers support a fix for this annoying problem. Inferior browsers like Internet Explorer is known not to support such a useful feature, though.

> var o = {a:5, b:9, c:2};
> var ol = Object.keys(o);
> ol
.. ["a", "b", "c"]
> ol.length
.. 3

Cool? The Object.keys() static method accepts an objects and returns an array of natively defined keys of the objects, those which pass the hasOwnProperty() test. Just count the length of the returned array, and you have the size of the object / number of items or properties in the object.

6 Responses to “JavaScript: get the number of properties in an object WITHOUT LOOPING”

  1. Sandeepan Kundu says:

    Very interesting way to get the object’s self properties.
    Object.keys(o) contains only properties/functions that are not inherited.

  2. chris says:

    and it will not work in browsers without ECMAScript 5 like IE 8 that is shipped with the still popular Windows 7 and anything before that you can forget.
    So make sure you use a polyfil; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

  3. Captain says:

    IE, the bane of the Web! Thanks for the input, Chris.

  4. Chaoran says:

    This is even more slower than a loop.

  5. Kirby Banman says:

    Chaoran is right. In fact, the fugly for loop is the fastest way by an order of magnitude: http://jsperf.com/counting-object-properties

    Do you want readable vanilla JS, or saved milliseconds?

    Your choice;]

  6. CoursesWeb says:

    Thank you for this yip, it was what i searched for.

Make a Comment