I've got an object filled with objects and I want to know how many items are in it. How can I do this with JS? Also running jQuery in the page.
Asked
Active
Viewed 296 times
3 Answers
6
Try this:
function countProperties(obj) {
var count = 0;
for (var prop in obj) {
if (obj.hasOwnProperty(prop))
++count;
}
return count;
}
-
You're welcome, glad to help. And by the way, it would be appreciated if you accepted my answer. Thanks. – Kevin Ji Apr 04 '11 at 23:30
-
Just did, sorry you were too fast and I had to wait out the 5 min clock :) – wesbos Apr 05 '11 at 03:37
-1
"object filled with objects" is more commonly known as an array. Anyway:
yourObject.length

Jim Blackler
- 22,946
- 12
- 85
- 101
-
An array is also an object. `b = new Array(); typeof b` displays `"object"` – Jim Blackler Apr 04 '11 at 23:25
-
See my answer below; by "array" I mean the "Array()" object https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array And also, length is a property of only the Array object, not the Object object – Kevin Ji Apr 04 '11 at 23:26
-
I wholeheartedly disagree. yes, an array is an object. no, an object is not an array. `var x = {a:1}; console.log(x.length); // undefined` – Madbreaks May 31 '12 at 22:44