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.
You may use something like Lodash lib and _.toLength(object) should give you the length of your object
If you want to avoid new dependencies you could make your own smart objects. Of course only if you want to do more that just get it's size.
In jQuery i've made it in a such way:
For browsers supporting Object.keys() you can simply do:
Otherwise (notably in IE < 9), you can loop through the object yourself with a
for (x in y)
loop: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.Also can be done in this way:
For example:
Can be done easily with
$.map()
: