Back to: JavaScript Tutorial For Beginners and Professionals
How to Find the Length of a JavaScript Object
In this article, I am going to discuss How to Find the Length of a JavaScript Object with Examples. Please read our previous article where we discussed Traversing and Enumerate JavaScript Object Properties. In the previous article, we already saw, how we can get all properties or traverse an object’s properties using 5 different ways i.e.:
- for… in loops
- Object.keys(objectName)
- Object.values(objectName)
- Object.entries(objectName)
- Object.getOwnPropertyNames(objectName)
There are two ways we can find the length of a JavaScript object:
- Using the Object.keys() method
- Using the Object.getOwnPropertyNames() method
Using Object.keys() method to find the length of a JavaScript Object
Now we will see how we can get the length of the object using Object.keys(objectName). The length property is used to get the number of property keys that exist in the object or the size of an object. It gives the length of the object. This method was introduced in JavaScript ECMAScript5. The Object.keys() method takes the object as an argument of which properties keys are to be returned. It creates and returns an array that contains all the properties keys of the given object.
Once the object has been converted into an array using the Object.keys() method, we can loop through this array in the same way we do for a normal array using for… of loop.
Step1: Convert the object to get either its key, value, or both.
Step2: Loop through using for… of loop.
Syntax: Object.keys(obj).length
Parameter:
- Obj – it is an object name whose properties keys are to be returned.
- Object.keys() method returns an array that contains all the properties keys of the given object.
The length property is used to get the number of property keys that exist in the object or the size of an object. It gives the length of the object. What we discussed above is given in the below example.
Example1: JavaScript Objects, Object.keys() method iterate property keys of simple array & get the length of an array
<html> <head> <title>JavaScript Objects, Object.keys() method iterate property keys of simple array & get length of an array example1</title> </head> <body> <script> // Returning enumerable property keys of a simple array var covidYears = ['2019', '2020', '2021']; console.log('The properties of array covidYears: ', Object.keys(covidYears)); //returns all properties of an array console.log('The length of array covidYears: ', Object.keys(covidYears).length); //returns no. of items present in an array //looping through arrays created from Object.keys() method const cY = Object.keys(covidYears); for (let key of cY) { console.log(`The property keys of array covidYears: ${key}`) } </script> </body> </html>
Output:
In this example, an array “covidYears” has three property values [‘2019’, ‘2020’, ‘2021’] and the Object.keys() method returns the enumerable property keys of this array. And Object.keys(covidYears).length property returns a length of an array i.e.: 3. What we discussed above is given in the below example.
Example2: JavaScript Objects, Object.keys() method iterate property keys of array-like object & get the length of the object
<html> <head> <title>JavaScript Objects, Object.keys() method iterate property keys of array-like object & get the length of the object example2</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property keys of an array like object. let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //display data console.log("person object: ", person) console.log("person object length: ", Object.keys(person).length) //returns no. of keys present in an object console.log("person Object literal type? : ", typeof person);// object console.log('The key of person object property is: ', Object.keys(person)); //returns an array of all properties //Looping through arrays created from Object.keys() method //getting the keys/property const Pers = Object.keys(person); for (let key of Pers) { console.log("Looping through keys of arrays Pers created from Object.keys() method -->", key); // to print only object property keys/names } </script> </body> </html>
Output:
In this example, an array like object “person” has 5 property values {firstName: “Elon”, lastName: “Musk”, age: 25, location: “India”, pincode: 400001 }; and the Object.keys() method returns the enumerable property keys of this array. And Object.keys(person).length property returns a length of an array-like object i.e.: 5.
Object.keys() is used for returning property keys of an array-like object with random numeric property key ordering. Array-like object with random property key ordering, when using numeric property keys, the property keys are returned in the numerical order of keys that is in the ascending order of object’s property keys. What we discussed above is given in the below example.
Example3: JavaScript Objects, Object.keys() method iterate property keys of an array-like object with random property key ordering & get the length of the object
<html> <head> <title>JavaScript Objects, Object.keys() method iterate property keys of array-like object with random property key ordering get the length of the object example3</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property keys of an array like object with random property key ordering. var randomObj = { 70: 'one', 21: 'two', 35: 'three' }; //display data console.log("Random key object: ", randomObj) console.log("Random Key object length: ", Object.keys(randomObj).length) //returns no. of keys present in an object console.log("Random key Object literal type? : ", typeof randomObj);// object console.log('The keys of Random object property is: ', Object.keys(randomObj)); //returns an array of all property keys //[21, 35, 70] //Looping through arrays created from Object.keys() method //getting the property keys const Rand = Object.keys(randomObj); for (let key of Rand) { console.log("Looping through keys of arrays Rand created from Object.keys() method -->", key); // to print only object property keys } </script> </body> </html>
Output:
In this example, an array-like object “randomObj” has three property keys {70: ‘one’, 21: ‘two’, 35: ‘three’}; in random ordering and the Object.keys() method returns the enumerable property keys of this array in the ascending order of the object’s property keys. And Object.keys(randomObj).length property returns a length of an array-like object i.e.: 3.
We cannot call length property on an Object.
We might be thinking why can’t we just simply call length directly on our object. Let’s see what happens when we do:
<html> <head> <title>We cannot call length property on an Object</title> </head> <body> <script> const randomObj = { 70: 'one', 21: 'two', 35: 'three' }; console.log(randomObj.length); // undefined console.log(randomObj.hasOwnProperty('length')); // false </script> </body> </html>
Output:
we can’t do it by directly calling length property on an object this is because the object doesn’t have a length property. Only string and array contain length property.
Using Object.getOwnPropertyNames() method to find the length of a JavaScript Object
Next, we will see how we can get the length of the object using Object.getOwnPropertyNames(). The length property is used to get the number of property keys that exist in the object or the size of an object. It gives the length of the object.
In JavaScript Object.getOwnPropertyNames() method is an in-built method that takes the object as an argument, which returns an array containing all the properties names present in the given or passed object. The properties of an object include both fields (objects) as well as functions.
Syntax: Object.getOwnPropertyNames(obj).length;
Parameter: Obj – it is an object name whose property’s names are to be returned.
Object.getOwnPropertyNames() method returns an array containing all the properties names present in the given or passed object. The properties of an object include both fields (objects) as well as functions. The length property is used to get the number of property keys that exist in the object or the size of an object. It gives the length of the object. What we discussed above is given in the below example.
Example1: JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of simple array & get the length of an array
<html> <head> <title>JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of the simple array & get the length of an array example1</title> </head> <body> <script> // Returning enumerable property [key, value] pairs of a simple array var covidYears = ['2019', '2020', '2021']; console.log('The sorted property names of array covidYears: ', Object.getOwnPropertyNames(covidYears).sort()); //sort() is an array method to sort alphabetically console.log("Length of array covidYears: ", covidYears.length) //returns no. of item present in an array //Logging property names and values using Array.forEach loop Object.getOwnPropertyNames(covidYears).forEach( function (val, index, array) { console.log(`Looping property names & values of an array covidYears created from Object.getOwnPropertyNames() method: ${val} : ${covidYears[val]}`); }); </script> </body> </html>
Output:
In this example, an array “covidYears” has three property values [‘2019’, ‘2020’, ‘2021’] and the Object.getOwnPropertyNames() method returns the enumerable property names of this array. Hence it returns an array of all property’s names present in the given simple array i.e.: [“0”, “1”, “2”, “length”] where 0,1, and 2 are the indexes as the key of the element 2019, 2020 and 2021 values respectively in the simple array and as the array have inbuilt length property it gives the number of elements present in the array or the size of an array. Sort() method is an array method used to sort the array in an ascending order based on properties keys. And array in-built covidYears.length property returns the length of an array i.e.: 3. What we discussed above is given in the below example.
Example2: JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of arrays like object & get the length of the object
<html> <head> <title>JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of arrays like object example2</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property names of an array like object. let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //display data console.log("person object: ", person) console.log("person object length: ", Object.getOwnPropertyNames(person).length) //returns no. of keys present in an object console.log("person object sorted properties names: ", Object.getOwnPropertyNames(person).sort()) //sort() is an array method to sort alphabetically console.log("person Object literal type? : ", typeof person);// object //Logging property names and values using Array.forEach Object.getOwnPropertyNames(person).forEach( function (val, index, array) { console.log(`Looping property names & values of an array person created from Object.getOwnPropertyNames() method: ${val} : ${person[val]}`); }); </script> </body> </html>
Output:
In this example, an array-like object “person” has 5 property values {firstName: “Elon”, lastName: “Musk”, age: 25, location: “India”, Pincode: 400001 }; and the Object.getOwnPropertyNames() method returns the enumerable property names of this array-like object. Hence it returns an array of all property’s names present in the given array-like object i.e.: [“age”, “firstName”, “lastName”, “location”, “Pincode”] where age, firstName, lastName, location, and Pincode are the sorted property names in the array-like object. It is sorted as we have used the sort() method to sort an array in an ascending order based on properties keys. And the Object.getOwnPropertyNames(person).length property gives the number of property keys present in the object or the size of an object or the length of the object.
Object.keys vs Object.getOwnPropertyNames in JavaScript
The difference is that the Object.getOwnPropertyNames() method will return ALL property keys, whereas Object.keys() methods will just return the enumerable property keys. What we discussed above is given in the below example.
Example: JavaScript Objects, Object.keys vs Object.getOwnPropertyNames
<html> <head> <title>JavaScript Objects, Object.keys vs Object.getOwnPropertyNames example</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property names of an array like object. let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //method defineProperty() to add property to an object or modifies attributes of an existing property //setting enumerable attribute to false so it won’t get enumerate Object.defineProperty(person, 'propertyKey', { value: 'value1', enumerable: false, }); //display data console.log("person object: ", person) console.log("person object length: ", Object.getOwnPropertyNames(person).length) //returns no. of keys present in an object console.log("person object properties names using Object.keys: ", Object.keys(person)) // return the enumerable property keys. console.log("person object properties names using Object.getOwnPropertyNames: ", Object.getOwnPropertyNames(person)) //return ALL property keys console.log("person Object literal type? : ", typeof person);// object </script> </body> </html>
Output:
In the above code, we have used the previous chapter example object sample and then we have added another new property and set its attribute enumerable to false using Object.defineProperty(), (about Object.defineProperty() method will see this in detail in Object.defineProperty() chapter) later we are fetching the object person properties by using Object.keys(person) method and by using Object.getOwnPropertyNames(person) method.
If we noticed in the above code output with the highlighted text that when using Object.keys(person) method returns the enumerable property keys whose inbuilt enumerable property is true by default whereas Object.getOwnPropertyNames(person) method return all the property keys irrespective of if we have explicitly set the enumerable attribute to false then too.
In this article, I am going to discuss Object Property Initializer Shorthand from Variables in JavaScript with Examples. Here, in this article, I try to explain How to Find the Length of a JavaScript Object with Examples and I hope you enjoy this How to Find the Length of a JavaScript Object article.