In JavaScript, an object is an unordered collection of key-value pairs. These key-value pairs are called the properties of the object.
Most of the time, when we are working with such objects, we need to know the size of the object i.e. the total number of properties that the object has.
But, like the arrays and strings, there is no .length
property for objects. If you try to get the length of the object using the .length
property, it will return undefined
.
const obj = { name: 'John', age: 24, gender: 'Male' } console.log(obj.length) // Output: undefined
As you can see from the above example when we tried to access the size of the object using the .length
property, it returned undefined
.
In this article, we will go through two most commonly used methods to get the size of an object in JavaScript.
Get the Object’s Length using the Object.keys() Method
The Object.keys()
method returns an array containing each key of the specified object.
So, if we want to get the length of an object, we can first get its keys using the Object.keys()
method and then apply the .length
property on the keys array to get its length.
const obj = { name: 'John', age: 24, gender: 'Male' } // Get object's keys const keys = Object.keys(obj); console.log(keys); // ["name", "age", "gender"] // Object's size console.log(keys.length); // 3
Get the Object’s Length using a For… In Loop
This is an old approach to get the length of an object. In this method, we loop through the object keys using a for...in
loop and increment the count by 1 every time the loop runs.
The total count of the object’s keys represents the size of the specified object.
const obj = { name: 'John', age: 24, gender: 'Male' } // Set count to 0 initially let count = 0; for(let key in obj){ count ++; } // Object's Length console.log(count); // 3
Conclusion
In this article, we learned two easy ways to get the length of an object in JavaScript.
The first approach is to get all the keys of the given object using the Object.keys()
method and then apply the .length
property on the keys array returned by the Object.keys()
method.
The second approach is to loop through the object keys using a for...in
loop and count the total number of keys in the object. The total number of keys represents the size of the given object.