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.
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
.
var l={"a":1,"b":2,"c":5};
Object.keys(l).length;
function count(O){
for(var p in O){
if(O.hasOwnProperty(p))++cnt;
}
return cnt;
}
count(l);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With