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
How to get the size of a json object in JavaScript?
In this article, we will learn about various methods to get the size of a JSON object in JavaScript.
Getting the size of a JSON object in JavaScript is the same as counting the total number of keys in an object. We can accomplish this using several different approaches.
Using Object.keys() (Recommended)
The Object.keys() method returns an array of the given object's enumerable property names. To get the size, we simply check the length of this array.
Syntax
Object.keys(objectName).length
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Size of JSON Object</title>
</head>
<body>
<script>
var myObject = {
name: "tutorialspoint",
address: "above D-mart",
city: "hyderabad",
country: "India"
};
var size = Object.keys(myObject).length;
document.write("Object size: " + size);
</script>
</body>
</html>
Object size: 4
Using the for...in Loop
The for...in loop iterates over all enumerable properties of an object. We can use a counter variable to track the number of properties.
Syntax
for (let key in object) {
// increment counter
}
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Size of JSON Object</title>
</head>
<body>
<script>
let myObject = {
name: "tutorialspoint",
address: "above D-mart",
city: "hyderabad",
country: "India"
};
let count = 0;
for (let key in myObject) {
count++;
}
document.write("Object size using for...in: " + count);
</script>
</body>
</html>
Object size using for...in: 4
Using hasOwnProperty() for Accuracy
To ensure we only count the object's own properties (not inherited ones), we can combine for...in with hasOwnProperty().
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Size of JSON Object</title>
</head>
<body>
<script>
Object.size = function(obj) {
var size = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
var myObject = {
name: "tutorialspoint",
address: "above D-mart",
city: "hyderabad",
country: "India"
};
var size = Object.size(myObject);
document.write("Object size with hasOwnProperty: " + size);
</script>
</body>
</html>
Object size with hasOwnProperty: 4
Comparison of Methods
| Method | Performance | Handles Inheritance | Recommended |
|---|---|---|---|
Object.keys().length |
Fast | Yes (own properties only) | Yes |
for...in loop |
Slower | No (includes inherited) | No |
for...in with hasOwnProperty()
|
Slower | Yes (own properties only) | For legacy support |
Conclusion
Object.keys().length is the most efficient and recommended method to get the size of a JSON object in JavaScript. It's concise, performs well, and automatically handles inherited properties correctly.
