patrick
patrick

Reputation: 11711

Getting length of an object

I have the following object:

var l={"a":1,"b":2,"c":5};

I want to get the length of this

alert(l.length);

but that returns undefined. Obviously I'm looking to get 3 as the answer.

Upvotes: 5

Views: 248

Answers (3)

kennebec
kennebec

Reputation: 104760

function count(O){
    for(var p in O){
        if(O.hasOwnProperty(p))++cnt;
    }
    return cnt;
}
count(l);

Upvotes: 1

Eric
Eric

Reputation: 97555

You can count the number of entries in an object using Object.keys(), which returns an array of the keys in the object:

var l = {a: 1, b: 2, c: 3};
Object.keys(l).length;

However, it might be more efficient (and cross browser) to implement your own property:

Object.length = function(obj) {
    var i = 0;
    for(var key in obj) i++;
    return i;
}

Object.length(l);

Note that although I could have defined the function as Object.prototype.length, allowing you to write l.length(), I didn't, because that would fail if your object container the key length.

Upvotes: 11

thecodeparadox
thecodeparadox

Reputation: 87073

var l={"a":1,"b":2,"c":5};
Object.keys(l).length;

Upvotes: 1

Related Questions