How to check if the object is empty using JavaScript
In javascript, we can use the Object.getOwnPropertyNames()
method to check if the given object is empty or not.
function isObjectEmpty(obj){
return Object.getOwnPropertyNames(obj).length >= 1}
isObjectEmpty({ }) // false
isObjectEmpty({id:1,name:"js"}) // true
If we pass an object to the Object.getOwnPropertyNames()
method it returns an array of object properties.so that by using the length of that array we can easily check if the given object is empty or not.
Similarly, we can use the Object.keys()
or Object.values()
method.
Example:
Object.values({ }).length >= 1 // false
Object.values({ id:1}).length >= 1 // true
Object.keys({id:1 }).length >=1 // true
-
The
Object.keys()
method returns an array with object keys. -
The
Object.values()
method returns an array with object values.