Getting the 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 it returns undefined. Obviously, I hope to get 3as an answer.

+5
source share
3 answers

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

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

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

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

Object.length(l);

Please note that although I could define the function as Object.prototype.lengthwhat allows l.length()me to write , I did not do this because it will not succeed if there is a key in your object container length.

+11
source
var l={"a":1,"b":2,"c":5};
Object.keys(l).length;
+1
source
function count(O){
    for(var p in O){
        if(O.hasOwnProperty(p))++cnt;
    }
    return cnt;
}
count(l);
+1
source

All Articles