How to get object length [duplicate]
Is there any built-in function that can return the length of an object?
For example, I have a = { 'a':1,'b':2,'c':3 }
which should return 3
. If I use a.length
it returns undefined
.
It could be a simple loop function, but I'd like to know if there's a built-in function?
There is a related question (Length of a JSON object) - in the chosen answer the user advises to transform object into an array, which is not pretty comfortable for my task.
Solution 1:
For browsers supporting Object.keys() you can simply do:
Object.keys(a).length;
Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y)
loop:
var count = 0;
var i;
for (i in a) {
if (a.hasOwnProperty(i)) {
count++;
}
}
The hasOwnProperty
is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.
Solution 2:
This should do it:
Object.keys(a).length
However, Object.keys
is not supported in IE8 and below, Opera and FF 3.6 and below.
Live demo: http://jsfiddle.net/simevidas/nN84h/
Solution 3:
Can be done easily with $.map()
:
var len = $.map(a, function(n, i) { return i; }).length;
Solution 4:
Have you taken a look at underscore.js (http://underscorejs.org/docs/underscore.html)? It's a utility library with a lot of useful methods. There is a collection size
method, as well as a toArray method, which may get you what you need.
_.size({one : 1, two : 2, three : 3});
=> 3