Javascript check is object is empty

How to check if an object is empty in JavaScript

For JavaScript objects, there is no built-in .length or .isEmpty method available to check if they are empty.

Here are 4 different methods that you can use to make sure that a given object does not have its own properties:

The Object.entries() method takes an object as an argument and returns an array of its enumerable property Javascript check is object is empty pairs. We can then use the .length property of the array to check if it contains any item:

const user = > Object.entries(user).length === 0 // true const bird =  name: 'Penguin', avatar: '🐧' > Object.entries(bird).length === 0 // false 

Note: Object.entries() only works in modern browsers and is not supported by IE. If you need backward compatibility, consider adding a polyfill or use Oject.keys() method instead.

The Object.keys() method is the best way to check if an object is empty because it is supported by almost all browsers, including IE9+. It returns an array of a given object’s own property names. So we can simply check the length of the array afterward:

Object.keys(>).length === 0 // true Object.keys( name: 'Atta' >).length === 0 // false 

The Object.getOwnPropertyNames() method takes an object as parameter and returns an array of its own property names:

Object.getOwnPropertyNames(>).length === 0 // true Object.getOwnPropertyNames( id: 1, name: 'John Doe' >).length === 0 // false 

If you are already using 3rd-party libraries like jQuery or Lodash in your web application, you can also use them to check if an object is empty:

// jQuery jQuery.isEmptyObject(>) // true jQuery.isEmptyObject( id: 1, name: 'John Doe' >) // false // Lodash _.isEmpty(>) // true _.isEmpty( name: 'Emma' >) // false 
Object.prototype.isEmpty = function ()  return Object.keys(this).length == 0 > 

Now you can call the isEmpty() method on any JavaScript object to check if it has its own properties:

const obj = > obj.isEmpty() // true const site =  title: 'Twitter', website: 'https://twitter.com' > site.isEmpty() // false 

Be careful while extending the Object prototype, as it can cause issues when used together with other JavaScript frameworks. Instead, use the Object.keys() method in JavaScript applications to check if an object is empty. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

How to Check if an Object is Empty in JavaScript – JS Java isEmpty Equivalent

Joel Olawanle

Joel Olawanle

How to Check if an Object is Empty in JavaScript – JS Java isEmpty Equivalent

An object is one of the most commonly used data types in programming. An object is a collection of related data stored as key-value pairs. For example:

When working with objects, you may need to check if an object is empty before performing a function.

In JavaScript, there are various ways you can check if an object is empty. In this article, you will learn the various ways you can do this, the options that can be attached, and why.

Note: An object is considered empty when it has no key-value pair.

In case you are in a rush, here is a basic example:

const myEmptyObj = <>; // Works best with new browsers Object.keys(myEmptyObj).length === 0 && myEmptyObj.constructor === Object // Works with all browsers _.isEmpty(myEmptyObj) 

Both methods will return true . Let’s now understand these and more options you can use to check if an object is empty in JavaScript.

How to Check if an Object is Empty with Object.keys()

The Object.keys() method is a static object method introduced in ECMAScript6 (ES6) and is supported in all modern browsers. This method returns an array with the keys of an object. For example:

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; console.log(Object.keys(userDetails)); // ["name","username","age"] 

With this, you can now apply the .length property. If it returns zero (0), the object is empty.

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; console.log(Object.keys(userDetails).length); // 3 console.log(Object.keys(myEmptyObj).length); // 0 

You can now use this method to check if an object is empty with an if statement or create a function that checks.

const isObjectEmpty = (objectName) =>

This will return either true or false . If the object is empty, it will return true , otherwise, it will return false .

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return Object.keys(objectName).length === 0 >console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

Note: Checking the length alone is not the best option when checking if an object is empty or for any datatype. It is always best to confirm if the data type is correct.

To do this, you can use the constructor check:

const isObjectEmpty = (objectName) =>

This way, you are liable to get a more thorough check.

Thus far, everything has worked fine. But you might also want to avoid throwing a TypeError when a variable is undefined or a value of null is passed instead of <> . To fix this, you can add an extra check:

const isObjectEmpty = (objectName) => < return ( objectName && Object.keys(objectName).length === 0 && objectName.constructor === Object ); >; 

In the code above, an extra check is added. This means that it will return either null or undefined if it is not an empty object, as shown in the example below:

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; let nullObj = null; let undefinedObj; const isObjectEmpty = (objectName) => < return ( objectName && Object.keys(objectName).length === 0 && objectName.constructor === Object ); >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true console.log(isObjectEmpty(undefinedObj)); // undefined console.log(isObjectEmpty(nullObj)); // null 

Note: This applies to other object static methods, meaning you can make use of Object.entries() or Object.values() instead of Object.keys() .

How to Check if an Object is Empty with a for…in Loop

Another method you can use is the ES6 for…in loop. You can use this loop alongside the hasOwnProperty() method.

const isObjectEmpty = (objectName) => < for (let prop in objectName) < if (objectName.hasOwnProperty(prop)) < return false; >> return true; >; 

The method above will loop through each object property. If it finds a single iteration, the object is not empty. Also, the hasOwnProperty() will return a boolean indicating whether the object has the specified property as its property.

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < for (let prop in objectName) < if (objectName.hasOwnProperty(prop)) < return false; >> return true; >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

How to Check if an Object is Empty with JSON.stringify()

You can also make use of the JSON.stingify() method, which is used to convert a JavaScript value to a JSON string. This means it will convert your object values to a sting of the object. For example:

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; console.log(JSON.stringify(userDetails)); Output: "" 

This means when it is an empty object, then it will return «<>» . You can make use of this to check for an empty object.

const isObjectEmpty = (objectName) => < return JSON.stringify(objectName) === "<>"; >; 

This will return true if the object is empty, otherwise false :

let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return JSON.stringify(objectName) === "<>"; >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

How to Check if an Object is Empty with Lodash

Finally, some of the methods I’ve explained here might work for older browser versions, while others may not work. If you are concerned about a solution that will work for both old and modern browser versions, you can use Lodash.

Lodash is a modern JavaScript utility library that can perform many JavaScript functionalities with very basic syntax.

For example, if you want to check if an object is empty, you only need to use the «isEmpty» method.

Installing Lodash into your project is quite easy. All you have to do is make use of this command:

You can now initialize the underscore method and make use of this method.

const _ = require('lodash'); let userDetails = < name: "John Doe", username: "jonnydoe", age: 14 >; let myEmptyObj = <>; const isObjectEmpty = (objectName) => < return _.isEmpty(objectName); >; console.log(isObjectEmpty(userDetails)); // false console.log(isObjectEmpty(myEmptyObj)); // true 

That’s It! 💪

I’ve enjoyed exploring the various ways you can check if an object is empty. Feel free to use the best method that fits your project or task.

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

Источник

5 Ways to Check If an Object Is Empty in JavaScript

K. Jagathish is a front end developer who has worked in tech for more than five years. He’s currently a developer at Tata Consultancy Services.

javascript-check-if-object-is-empty

In this article you will learn five different ways to check if an object is empty in JavaScript. Let’s jump right in.

How to Check If an Object Is Empty in JavaScript

  1. Use Object.keys
  2. Loop Over Object Properties With for…in
  3. Use JSON.stringify
  4. Use jQuery
  5. Use Underscore and Lodash Libraries

1. Use Object.keys

Object.keys will return an array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.

We can also check this using Object.values and Object.entries . This is typically the easiest way to determine if an object is empty.

More From Built In Experts Fauna: An Introduction

2. Loop Over Object Properties With for…in

The for…in statement will loop through the enumerable property of the object.

function isEmpty(obj) < for(var prop in obj) < if(obj.hasOwnProperty(prop)) return false; >return true; >

In the above code, we will loop through object properties and if an object has at least one property, then it will enter the loop and return false. If the object doesn’t have any properties then it will return true.

Tutorials for Software Developers on Built In Create React App and TypeScript — A Quick How-To

3. Use JSON.stringify

If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.

function isEmptyObject(obj)< return JSON.stringify(obj) === '<>' >

4. Use jQuery

5. Use Underscore and Lodash Libraries

These five quick and easy ways to check if an object is empty in JavaScript are all you need to get going.

Источник

Читайте также:  Разработка java среда разработки
Оцените статью