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.
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
We can also check this using Object.values
and Object.entries
.
This is typically the easiest way to determine if an object is empty.
The for…in
statement will loop through the enumerable property of 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.
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) === '{}';
}
jQuery.isEmptyObject(obj);
_.isEmpty(obj);
#javascript #Object #programming