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.
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.You might have an undefined property in the object. If using the method of
Object.keys(data).length
is used those properties will also be counted.You might want to filter them out out.
You could add another name:value pair of length, and increment/decrement it appropriately. This way, when you need to query the length, you don't have to iterate through the entire objects properties every time, and you don't have to rely on a specific browser or library. It all depends on your goal, of course.
Summarizing all together, here is a universal function (including ie8 support):
For those coming here to find the item count of something that is already a jQuery object:
.length is what you are looking for:
Example:
Here's a jQuery-ised function of Innuendo's answer, ready for use.
Can be called like this: