I'm trying to use JavaScript object as an associative array and everything was well until I needed to get number of entries that are stored in it. What is the easiest and most elegant way to do that? All I can think of is to run for each
loop or jQuery $.each
function and just see how much iterations it would do but that looks like an an awful thing to do.
views:
141answers:
4It comes down to that, or keeping count when you add and delete properties from the object.
unfortunately there isn't really a good way to know the number of properties in an object without iterating over them. The following is fairly simple though:
function countProps(obj) {
var l = 0;
for (p in obj) l++;
return l;
}
var bob = { a: 1, b: 2};
alert(countProps(bob));
I believe this has been answered on here before, and/or googling can lead you in the right direction. Nevertheless let me point out that one of the biggest gotchas if you use a loop in the form of:
for (var attr in obj) { ....
Is that the object could be cluttered with properties you did not necessarily add, and the standard solution to this as I recall is to additionally use the test for hasOwnProperty, see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty
Firefox supports the count property. In other browsers the following solution should suffice:
function count(obj) {
if (obj.__count__ !== undefined) {
return obj.__count__;
}
var c = 0, p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
c += 1;
}
}
return c;
}