Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting length of an object

Tags:

javascript

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.

like image 395
patrick Avatar asked May 17 '12 18:05

patrick


3 Answers

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.

like image 122
Eric Avatar answered Oct 01 '22 01:10

Eric


var l={"a":1,"b":2,"c":5};
Object.keys(l).length;
like image 24
thecodeparadox Avatar answered Oct 01 '22 02:10

thecodeparadox


function count(O){
    for(var p in O){
        if(O.hasOwnProperty(p))++cnt;
    }
    return cnt;
}
count(l);
like image 27
kennebec Avatar answered Oct 01 '22 02:10

kennebec