Blog

Counting number of properties in a JS object

When there is a JS array, it is easy to count the number of elements. For example:


var arr = ["hello", "world"];
console.log(arr.length);
// 2

However, when you have an object it is a bit more tricky. .length wont work.
One way is to iterate through the object like this:

var obj = {
prop1:"hello",
prop2:"world"
};
var count = 0;
for (i in obj) { count++ }; // count is 2

However, if you use jQuery’s map() function (jQuery 1.6 needed) there is another alternative, a bit more elegant:

$.map(obj, function(value, key) {
return key;
}).length;

Essentially you get an array with the keys of the object and you use .length on that array.

Note: ECMAScript5 supports Object.keys() but it’s not supported for pre-IE9 browsers

Tags > ,

1 Comment

  • Nikitas

    No need to use jQuery’s map, if you don’t need to, or right a loop for your self for that. You can use standard ES5 functions for this in the following way:

    var obj = { foo: 1, bar: 2 };
    var length = Object.keys(obj).length

    Reply

Post A Reply to Nikitas Cancel Reply