Larry Cinnabar Larry Cinnabar - 1 year ago 96
Javascript Question

How to get object length

Is there any built-in function that can return the length of an object?

For example, I have

a = { 'a':1,'b':2,'c':3 }
which should return
. If I use
it returns undefined.

It could be a simple loop function, but I'd like to know if there's a built-in function?

Thank you.

P.S. I found a related question (Length of a JSON object) - in the chosen answer the user advises to transform object in an array, which is not pretty comfortable for me.

Answer Source

For browsers supporting Object.keys() you can simply do:


Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y) loop:

var count = 0;
var i;

for (i in a) {
    if (a.hasOwnProperty(i)) {

The hasOwnProperty is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download