Home  >  Article  >  Web Front-end  >  How to check if an object is empty using JavaScript?

How to check if an object is empty using JavaScript?

王林
王林forward
2023-09-14 14:17:021479browse

如何使用 JavaScript 检查对象是否为空?

In JavaScript, objects are the most important data type and we need it most of the time when developing applications using JavaScript frameworks. Sometimes we need to check if an object is empty and perform operations based on the object value.

For example, you are getting data from the database; if it is not found, you can get an empty object. When you perform certain operations or perform certain methods on an empty object, it throws an error in your program. So it's better to check if the object is empty first.

We will learn three ways to check if an object is empty using JavaScript.

Use Object.keys() method

We can use the Object.keys() method to get the keys of objects in a single array. Afterwards, we can check the length of the array using its length property. If the length of the keys array is 0, it means that the object does not contain any keys and the object is empty.

grammar

Users can use the Object.keys() method according to the following syntax to check whether the object is empty.

let obj1Len = Object.keys(obj1).length;
if (obj1Len == 0) {
   
   // object is empty
} else {
   
   // object is not empty
} 

In the above syntax, Object.keys() returns an array of all keys of obj1, and we use the length property to get its length. Using the above syntax, we can get an array of all keys using the Object.keys() method, and we can also check the length of the array using the length property

Example

In the example below, we create two different objects. obj1 contains some properties, while obj2 is empty and does not contain any single property.

After that, we use the Object.keys() method on both objects to get the keys array and check the length of the array to make sure the object is empty or contains at least one property.

<html>
<body>
   <h3>Using the<i> object.keys() </i>method to check whether the object contains some value or not</h3>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      let obj1 = {
         prop1: 10,
         prop2: "Hi",
      };
      let obj2 = {};
      
      // get the array of all keys using the Object.keys() method,
      
      // check the length of the array using the length property
      let obj1Len = Object.keys(obj1).length;
      if (obj1Len != 0) {
         output.innerHTML += "The value of obj1 is " + JSON.stringify(obj1) + "</br>";
      } else {
         output.innerHTML += "The obj1 object is empty! </br>";
      }
      let obj2Len = Object.keys(obj2).length;
      if (obj2Len != 0) {
         output.innerHTML += "The value of obj1 is " + obj2 + "</br>";
      } else {
         output.innerHTML += "The obj2 object is empty! </br>"; 
      }
   </script>
</body>
</html>

Use for-in loop

for-in Loops allow us to iterate over the keys of an object. We can use for-in to loop through each key of the object. Here we will use for-in loop and check if it iterates over the object once, then the object contains at least one property and is not empty.

grammar

Users can use the for-in loop to check whether the object is empty according to the following syntax.

function isObjectEmpty(object) {
   for (ele in object) {
      
      // object is not empty
      return;
   }
   
   // if control comes here, the object is empty
} 

In the above syntax, if a single iteration of the for loop occurs, it means that we have ensured that the object contains at least one attribute. Therefore, we terminate the function using the return keyword after the first iteration of the for-in loop.

Example

In the example below, we create two different objects. Additionally, we created the isObjectEmpty() function that prints a different message depending on whether the object is empty or not.

We called the isObjectEmpty() function twice using different objects, and the user can observe its output.

<html>
<body>
   <h3>Using the <i>for-in loop</i> to check whether the object contains some value.</h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      
      // creating the objects
      let obj1 = {
         prop1: false,
      };
      let obj2 = {};
      
      // creating a function to check object is empty or not
      function isObjectEmpty(object) {
         for (ele in object) {
            
            // if any single iteration occurs using a for-in loop, it means the object contains at least one property
            output.innerHTML += "The object " + JSON.stringify(object) + " is not empty! </br>";
            return;
         }
         output.innerHTML += "The object " + JSON.stringify(object) + " is empty! </br>";
      }
      
      // calling the isObjectEmpty() function by passing different objects as an argument
      isObjectEmpty(obj1);
      isObjectEmpty(obj2);
   </script> 
</body>
</html>

Use JSON.stringify() method

JSON.stringify() method converts any value to the string we pass as the argument to the method. The syntax for an empty object is similar to {}, and the stringify() method always returns "{}" for an empty object.

Therefore, we can compare the return value of the stringify() method with "{}" to determine whether the object is empty.

grammar

Users can use the JSON.stringify() method according to the following syntax to check whether the object is empty.

if(JSON.stringify(education) == "{}") {
   
   // object is empty
} else {
   
   // object is not empty
}

In the above syntax, if the education object is empty, the JSON.stringify() method will return "{}".

Example

In the following example, we create the education object, which contains some properties. Therefore, the JSON.stringify() method will not return "{}", but will return the string value of the education object. Therefore, the user can observe the output showing that the education object is not empty.

<html>
<body> 
   <h3> Using the<i> JSON.stringify() method </i> to check whether object contains some value or not.</h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      
      // creating the objects
      let education = {
         totalYears: 12,
         school: "Online",
      };
      
      // convert object to string,
      
      // if object is empty, the JSON.stringify() method will return "{}"
      if (JSON.stringify(education) == "{}") {
         output.innerHTML += "Object is empty!";
      } else {
         output.innerHTML += "Education object is not empty!";
      }
   </script>
</body>
</html>

We learned three ways to check whether an object is empty. The first and third methods only require one line of code; the user needs to write 3 or 4 lines to use the second line. Therefore, it is better to use any one of the first and third methods for better code readability.

The above is the detailed content of How to check if an object is empty using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete