In Javascript, there is no straight forward way to check javascript object is empty or not.
Like
var str1 = '';
if(!str1){
// will run
}
console.log(!!str1); //false
var obj1 = {};
if(!obj1){
//will not run
}
console.log(!!obj1) // true
If you see above, an empty string will be considered as a falsy value but the empty objects will not be considered as falsy value.
So, let’s see how we can check object is empty or not
Object.keys method
Object.keys method will return an array of keys in the object
var obj1 = {
a:10
};
console.log(Object.keys(obj1));//["a"]
var obj2 = {}
console.log(Object.keys(obj2));//[]
console.log(Object.keys(obj1).length === 0);//length is not zero means object is not emppty
console.log(Object.keys(obj2).length === 0); // length is zero means object is empty
As you can see above we are using Object.keys method which returns an array of object keys.
On the array, we can check length of an array. If length is zero then the object is empty else object is not empty
Using for-in loop
we can use for in loop to check object is empty or not
var obj1 = {};
function isEmpty(obj1){
let isObjectEmpty = true;
for(let obj in obj1){
if(obj1.hasOwnProperty(obj)){
isObjectEmpty = false;
break;
}
}
return isObjectEmpty
}
console.log(isEmpty(obj1))
In the above code, we have created one function named as isEmpty which takes obj1 as a parameter.
In the function we are iterating over the object using a for-in loop, In that, we are checking any property present on an object or not, If present then we are returning false means object is not empty else is empty
If you are using any utility library kind of lodash then library provides inbuilt function like _.isEmpty which helps you to identify the object is empty or not