Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  127] [ 6]  / answers: 1 / hits: 26445  / 15 Years ago, thu, july 2, 2009, 12:00:00

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.


More From » javascript

 Answers
35

Old Firefox supports the __count__ property. Newer environments support ES5's Object.keys. For older environments we have to fallback to just iterating over the object and counting manually (ugh!):



function count(obj) {

if (obj.__count__ !== undefined) { // Old FF
return obj.__count__;
}

if (Object.keys) { // ES5
return Object.keys(obj).length;
}

// Everything else:

var c = 0, p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
c += 1;
}
}

return c;

}

[#99200] Saturday, June 27, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;