2

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.

enter image description here

wesbos
  • 25,839
  • 30
  • 106
  • 143

3 Answers3

6

Try this:

function countProperties(obj) {
    var count = 0;

    for (var prop in obj) {
        if (obj.hasOwnProperty(prop))
            ++count;
    }

    return count;
}

See also: Number of elements in a javascript object

Community
  • 1
  • 1
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
0

For ECMAScript 5-compatible agents, for example Chrome, try this:

var obj = {a:1, b:2, c:3};
console.log('Your object has ' + Object.keys(obj).length + ' elements in it');

// Your object has 3 elements in it

See also here.

Cheers

Community
  • 1
  • 1
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
-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