Length of a JavaScript object

Asked : Nov 17

Viewed : 63 times

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
javascript javascript-objects 
3 Answers

Updated answer

Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you 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.

Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.

Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.

Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols.

var person = {
  [Symbol('name')]: 'John Doe',
  [Symbol('age')]: 33,
  "occupation": "Programmer"
};

const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1

let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2

Older answer

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
const myObj = {}
var size = Object.size(myObj);

There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.

answered Jan 29


Updated: If you're using Underscore.js (recommended, it's lightweight!), then you can just do

_.size({one : 1, two : 2, three : 3});
=> 3

If not, and you 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) {
    // http://stackoverflow.com/a/6700/11236
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

answered Jan 29


Loop through all the fields of the object and check their property: The hasOwnProperty() method is used to return a boolean value indicating whether the object has the specified property as its own property. This method can be used to check if each key is present in the object itself. The contents of the object are looped through and if the key is present, the total count of keys is incremented. This gives the length of the object.

Syntax:

var key, count = 0;

// Check if every key has its own property
for (key in exampleObject) {
    if (exampleObject.hasOwnProperty(key))

        // If the key is found, add it to the total length
        count++;
}
objectLenght = count;

Example:

<!DOCTYPE html>
<html>
  
<head>
    <title>Length of a JavaScript object</title>
</head>
  
<body>
    <h1 style="color: green">GeeksforGeeks</h1>
      
    <b>Length of a JavaScript object</b>
      
    <p>
        exampleObject = {
            id: 1,
            name: 'Arun',
            age: 30,
            department: 'sales'
        }
    </p>
      
    <p>
        Click on the button to get
        the length of the object.
    </p>
      
    <p>
        Length of the object is:
        <span class="output"></span>
    </p>
  
    <button onclick="getObjectLength()">
        Get object length
    </button>
      
    <script>
        function getObjectLength() {
  
            // Declare an object
            exampleObject = {
                id: 1,
                name: 'Arun',
                age: 30,
                department: 'sales'
            }
  
            var key, count = 0;
  
            // Check if every key has its own property
            for (key in exampleObject) {
                if (exampleObject.hasOwnProperty(key))
  
                    // If key is found, add it
                    // to total length
                    count++;
            }
            objectLenght = count;
  
            document.querySelector('.output').textContent
                    = objectLenght;
        }
    </script>
</body>
  
</html>               

answered Jan 29


Login and Submit Your Answer
Browse other questions tagged  javascript  javascript-objects or ask your own question.