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 the object in JavaScript is same as the counting the total number of keys of an object. In general, we can get the size or number of keys of a JSON object in JavaScript by using two methods.

Using object.keys()

The object.keys() method returns an array of the given object of its countable properties name with the same order as we get as a normal loop. Following is the syntax of this method −

Object.keys(name_of_object).length;

Example

Following is an example to get the size of a JSON object in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Size of json</title>
</head>
<body>
   <script>
      var myObject = {
         name: "tutorialspoint",
         address: "above D-mart",
         city: "hyderabad",
      };
      var size = Object.keys(myObject).length;
      document.write(size);
   </script>
</body>
</html>

Using the for…in loop

The for…in loop iterates over all non-symbols, enumerable properties of an object. Following is the syntax of the for…in loop −

for (let key in myObject){ … }:

In the above for loop, the key is the property of the object and myObject is the name of the object.

Example

In here we are trying to print the size of a JSON object using the for…in loop.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Size of json</title>
</head>
<body>
   <script>
      let myObject = {
         name: "tutorialspoint",
         address: "above D-mart",
         city: "hyderabad",
      };
      let count = 0; //declaring count as 0
      for (let key in myObject) {
         count++;
      }
      document.write(count);
   </script>
</body>
</html>

Using for loop

We can also get the number of elements in a JSON object using the for loop to do so, you need to define a variable and loop through the object(if JSON assigns it to the JS object) and increment a variable on each loop execution. Once the loops have read all the elements of your object you can print the size.

Example

Let us see an example for this −

<!DOCTYPE html>
<html lang="en">
<head>
<title>Size of json</title>
</head>
<body>
   <script>
      Object.size = function (obj) {
         var size = 0,
         key;
         for (key in obj) {
            if (obj.hasOwnProperty(key)) size++;
        }
        return size;
      };
      var obj = {
         name: "tutorialspoint",
         address: "above D-mart",
         city: "hyderabad",
      };
      var size = Object.size(obj);
      document.write("The Object has a length of " + size);
   </script>
</body>
</html>

Updated on: 19-Dec-2022

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements