Checking for Empty Objects in JavaScript

how to check object is empty in javascript?

The JSON.stringify method is used to convert a JavaScript object to a JSON string. The keys method returns an array that contains an array of property names of the object under consideration.

How to check if JavaScript Object is empty?

check if an object is empty is by using a utility function
 

function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}

using the above function.

var lObject = {}; // Empty Object
if(isEmpty(lObject)) {
//Your Object is empty (Would return true in this example)
} else {
//Your Object is NOT empty
}

Alternatively

 

Object.prototype.isEmpty = function() {
for(var key in this) {
if(this.hasOwnProperty(key))
return false;
}
return true;
}

 

check if the object is empty
 

var lObject = {
myKey: "loveCalc"
}

if(lObject.isEmpty()) {
// Your Object is empty
} else {
// Your Object is NOT empty (would return false in this example)
}

I hope you get an idea about how to check object is empty in javascript.


 

#javascript 

Checking for Empty Objects in JavaScript
1.05 GEEK