javascript tutorial - [Solved-5 Solutions] Length of a javascript object - javascript - java script - javascript array



Problem:

If we have a JavaScript object, say

var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
click below button to copy the code. By JavaScript tutorial team

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:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an object
var size = Object.size(myArray);
click below button to copy the code. By JavaScript tutorial team

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

_.size({one : 1, two : 2, three : 3});
=> 3
click below button to copy the code. By JavaScript tutorial team

If not, and we don't want to mess around with Object properties for whatever reason, and are already using jQuery, a plugin is equally accessible:

$.assocArraySize = function(obj) {
    
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

click below button to copy the code. By JavaScript tutorial team

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.

if (!Object.keys) {
    Object.keys = function (obj) {
        var arr = [],
            key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                arr.push(key);
            }
        }
        return arr;
    };
}

Object.keys(obj).length;

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Length of a javascript object