javascript tutorial - [Solved-5 Solutions] Length of a javascript object - javascript - java script - javascript array
Problem:
If we have a JavaScript object, say
is there a built-in or accepted best practice way to get the length of this object?
Solution 1:
The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:
There's a sort of convention in JavaScript that we don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.
Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, we can use Object.keys() so the above code just becomes:
var size = Object.keys(myObj).length;
This doesn't have to modify any existing prototype since Object.keys() is now built in.
Solution 2:
If we know we don't have to worry about hasOwnProperty checks, we can do this very simply:
Object.keys(myArray).length
Solution 3:
Updated: If you're using Underscore.js (recommended, it's lightweight!), then we can just do
Solution 4:
Use something as simple as:
Object.keys(obj).length
It doesn't have to be difficult and definitely doesn't require another function to accomplish.
Solution 5:
Here's the most cross-browser solution.
This is better than the accepted answer because it uses native Object.keys if exists. Thus, it is the fastest for all modern browsers.