Getting length of an object

javascript

Solution

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`.

Problem

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.

Original source