4

Javascript: Check If an Object Empty – thisPointer

 2 years ago
source link: https://thispointer.com/javascript-check-if-an-object-empty/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Javascript: Check If an Object Empty

While working in javascript, we often encounter a requirement to determine if the object is empty. This check is required at times before operating on the properties or methods of the objects. This article discusses various ways to check if an object is empty using example illustrations.

Javascript objects are something that describes anything with properties and methods.

An object is empty when defined but does not contain any properties or methods in it. For example:

let myObject = {}
let myObject = {} 

Table of Contents:

Check If an Object is Empty using for in and hasOwnProperty()

Javascript’s hasOwnProperty() determines if the object has the specified property as its own property(not inherited). This method returns a boolean value.

Advertisements

vid5e62792b95ec8618094391.jpg?cbuster=1600267117
10 Sec
Lambda Functions in Python
liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTUjJaNypaZypyRcoWU9MTY0MDtmNmA1NSZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTAkMwx3JaN0YT0jJat9NDUmJax9MmI1JaZcZF9jYXNmRG9gYWyhPXRbnXNjo2yhqGVlLzNioSZmqWJJZD10nGympG9coaRypv5wo20zZGVvqWqJozZipz1uqGyiow0znXNBpHA9MCZlnT02QmY5NmY2NTUmNmQ2MTp0NmM3QmpmNxImMTqCNTQmMDqEN0I2NDMlMmAmMwMkMxQmMTMlMxQmMmMjNUYmMDM2N0Q3QwpmMmEmMwMmMmQmOTM2MmQmOTqEN0I0MmMkMmpmMwqEN0I1MmY0NDp2ODpjNwMmMmQlNmY2MTU3MmUmMDVBNTt0OTp1NTxmMwM5NmQ3RDqCNwI2MmY4NmI2RwZENwU3RDqCNmE2NDY1NmM2Qwp0NxY3MDqEN0I2RwZDNwx2RTp1Nmt3RDqCNTtmNDM1MmM3RDqCNTxmMmMlMmU3RDqCNwYmMTqEN0I0QmMkMmImNTMlMmE3REZFRxUzZGyunWQ9JaVmZXJJpEFxZHI9MTQkLwE2NC42Ml4kNwQzqXNypyVBPU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9NwFwZDJzYzVzMzQ0NSZwo250ZW50RzyfZUyxPTAzoWVxnWFQoGF5TGymqEyxPTAzoWVxnWFMnXN0SWQ9MCZxqXI9ODAjJzqxpHI9MCZaZHBlQ29hp2VhqD0znXNXZVBup3NHZHBlPTEzY2NjYT0jJzNwpGFDo25mZW50PSZwYaVmqGVlPTE2NDA4MmpjNwU2MmQzqWyxPVNyn2yhZG9TUGkurWVlNwFwZDJzYzZuOGZuNlZjqWJVpzj9nHR0pHMyM0EyMxYyMxZ0nGympG9coaRypv5wo20yMxZdYXZup2NlnXB0LWNbZWNeLWyzLWFhLW9vnzVwqC1yoXB0rSUlRvZzoG9uqFN0YXR1pm1zYWkmZSZynWRmpD1jpzVvnWQ=

Example:-

Check if the below objects are empty

  • personObject1 = { personFirstName : ‘George’, personLastName : ‘Smith’, dateOfBirth : ‘Nov 14 1984’ , city : ‘Santiago’ }
  • personObject2 ={}

Code:-

// function to check if the object is empty
function isObjectEmpty(_object)
let isEmpty = false;
for(let p in _object)
if(Object.prototype.hasOwnProperty.call(_object, p))
isEmpty = true;
return !isEmpty;
let personObject1 = { personFirstName : 'George',
personLastName : 'Smith',
dateOfBirth : 'Nov 14 1984' ,
city : 'Santiago'
let personObject2 = {} ;
//usage of the function
console.log(isObjectEmpty(personObject1)); //false
console.log(isObjectEmpty(personObject2)); //true
// function to check if the object is empty
function isObjectEmpty(_object) 
{
  let isEmpty = false;
  for(let p in _object) 
  {
    if(Object.prototype.hasOwnProperty.call(_object, p))
    {
      isEmpty = true;
    }
  }
  return !isEmpty;
}
let personObject1 =  { personFirstName : 'George',
                      personLastName  : 'Smith',
                      dateOfBirth     : 'Nov 14 1984' ,
                      city            : 'Santiago'
                    };
let personObject2 = {} ;    
//usage of the function
console.log(isObjectEmpty(personObject1));  //false
console.log(isObjectEmpty(personObject2));  //true

Output:-

false
false
true

Explanation:-

Here, in the above code, we created a function(isObjectEmpty) to check if the object is empty or not.
The function takes an object as the parameter and returns true if the object is empty. Else returns false.
Within the function, we are looping through all the properties of the object. Even if one property is found, the variable isEmpty gets assigned a value ‘true’.
Initially, isEmpty is assigned as false. In the end, the variable isEmpty is returned.

Note that this function can be used even before ECMAScript5.

Check If an Object is Empty using Object.keys()

Javascript’s Object.keys() will return an array of property names of the object iterated in the order as in a standard loop.

Javascript’s Object.getPrototypeOf() will return the internal [[Prototype]]] property of the specified object.

Example:-

Check if the below objects are empty

  • personObject1 = { personFirstName : ‘George’, personLastName : ‘Smith’, dateOfBirth : ‘Nov 14 1984’ , city : ‘Santiago’ }
  • personObject2 ={}

Code:-

// function to check if the object is empty
function isObjectEmpty(_object)
// null check
if(_object !== null)
return Object.keys(_object).length === 0 && Object.getPrototypeOf(_object) === Object.prototype;
return true;
let personObject1 = { personFirstName : 'George',
personLastName : 'Smith',
dateOfBirth : 'Nov 14 1984' ,
city : 'Santiago'
let personObject2 = {} ;
//usage of the function
console.log(isObjectEmpty(personObject1));//false
console.log(isObjectEmpty(personObject2));//true
// function to check if the object is empty
function isObjectEmpty(_object)
{
  // null check
  if(_object !== null)
  {
  return Object.keys(_object).length === 0 && Object.getPrototypeOf(_object) === Object.prototype;
  }
  return true;
}
let personObject1 =  { personFirstName : 'George',
                      personLastName  : 'Smith',
                      dateOfBirth     : 'Nov 14 1984' ,
                      city            : 'Santiago'
                    };
let personObject2 = {} ;    
//usage of the function
console.log(isObjectEmpty(personObject1));//false
console.log(isObjectEmpty(personObject2));//true

Output:-

false
false
true

Explanation:-

Here, in the above code, we created a function(isObjectEmpty) to check if the object is empty or not.
The function takes an object as the parameter and returns true if the object is empty. Else returns false.
Within the function, we are first checking if the object is null. If the object is not null we check for two statements. One is to find out that the length of the array returned by Object.keys ===0, and the second is to find out if the internal prototype property is equal to Object.prototype. Only if both the statements are true, object will be empty. If any statement is false, it means the object is not empty.

Note that this method can be used ECMAScript5 onwards.

Check If an Object is Empty using JSON.stringify()

The JSON.stringify() will convert a javascript object or value to a JSON string.

Example:-

Check if the below objects are empty

  • personObject1 = { personFirstName : ‘George’, personLastName : ‘Smith’, dateOfBirth : ‘Nov 14 1984’ , city : ‘Santiago’ }
  • personObject2 ={}

Code:-

// function to check if the object is empty
function isObjectEmpty(_object)
if(_object !== null)
return JSON.stringify(_object) === '{}';
return true;
let personObject1 = { personFirstName : 'George',
personLastName : 'Smith',
dateOfBirth : 'Nov 14 1984' ,
city : 'Santiago'
let personObject2 = {} ;
//usage of the function
console.log(isObjectEmpty(personObject1));//false
console.log(isObjectEmpty(personObject2));//true
// function to check if the object is empty
function isObjectEmpty(_object)
{
  if(_object !== null)
  {
  return JSON.stringify(_object) === '{}';
  }
  return true;
}
let personObject1 =  { personFirstName : 'George',
                      personLastName  : 'Smith',
                      dateOfBirth     : 'Nov 14 1984' ,
                      city            : 'Santiago'
                    };
let personObject2 = {} ;    
//usage of the function
console.log(isObjectEmpty(personObject1));//false
console.log(isObjectEmpty(personObject2));//true

Output:-

false
false
true

Explanation:-

Here, in the above code, we created a function(isObjectEmpty) to check if the object is empty or not.
The function takes an object as the parameter and returns true if the object is empty. Else returns false.
Within the function, we are first checking if the object is null. If the object is not null, we check for a statement JSON.stringify(_object) === ‘{}’ , which returns true if none of the property is found within the object. Else returns false.

Check If an Object is Empty in jQuery

JQuery is a javascript library.

jQuery.isEmptyObject({});
jQuery.isEmptyObject({}); 

This method will return true if the object is empty.

Check If an Object is Empty in lodash

lodash is a javascript utility library.

_.isEmpty({});
_.isEmpty({}); 

This method will return true if the object is empty.

Check If an Object is Empty in Underscore

Underscore is a javascript library that provides functional programming without extending built-in objects.

_.isEmpty({});
_.isEmpty({});

This method will return true if the object is empty.

Check If an Object is Empty in Ramda

Ramda is a javascript library of functions to add functional programming to javascript.

R.isEmpty({});
R.isEmpty({});

This method will return true if the object is empty.

I hope this article helped you check if the object is empty in javascript. Good Luck !!!

Advertisements


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK