Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the length of a JavaScript object
JavaScript objects don't have a built-in length property like arrays. However, there are several methods to find the number of properties in an object.
Suppose we have an object like this:
const obj = {
name: "Ramesh",
age: 34,
occupation: "HR Manager",
address: "Tilak Nagar, New Delhi",
experience: 13
};
We need to count the number of properties in this object.
Using Object.keys() (Recommended)
The most common and reliable method is Object.keys(), which returns an array of the object's property names:
const obj = {
name: "Ramesh",
age: 34,
occupation: "HR Manager",
address: "Tilak Nagar, New Delhi",
experience: 13
};
const length = Object.keys(obj).length;
console.log("Object length:", length);
Object length: 5
Using for...in Loop
You can manually count properties using a for...in loop with hasOwnProperty() to ensure you only count the object's own properties:
const obj = {
name: "Ramesh",
age: 34,
occupation: "HR Manager",
address: "Tilak Nagar, New Delhi",
experience: 13
};
function getObjectLength(obj) {
let count = 0;
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
count++;
}
}
return count;
}
console.log("Object length:", getObjectLength(obj));
Object length: 5
Using Object.entries()
Object.entries() returns an array of key-value pairs, so its length gives us the property count:
const obj = {
name: "Ramesh",
age: 34,
occupation: "HR Manager"
};
const length = Object.entries(obj).length;
console.log("Object length:", length);
console.log("Entries:", Object.entries(obj));
Object length: 3 Entries: [ [ 'name', 'Ramesh' ], [ 'age', 34 ], [ 'occupation', 'HR Manager' ] ]
Comparison
| Method | Performance | Readability | Recommended |
|---|---|---|---|
Object.keys().length |
Fast | Excellent | Yes |
for...in loop |
Slower | Good | For complex cases |
Object.entries().length |
Moderate | Good | When you need entries too |
Edge Cases
Be aware that these methods only count enumerable own properties:
const obj = {};
Object.defineProperty(obj, 'hidden', {
value: 'secret',
enumerable: false
});
obj.visible = 'public';
console.log("Keys count:", Object.keys(obj).length);
console.log("Keys:", Object.keys(obj));
Keys count: 1 Keys: [ 'visible' ]
Conclusion
Use Object.keys(obj).length as the standard way to find an object's property count. It's concise, readable, and performs well for most use cases.
