To check if an object is empty or not, you can use the built-in Object.keys()
method. The Object.keys()
method returns an array of all the keys that are present in the object.
So, if the length of the keys array is 0, it means the object is empty otherwise it is not.
See the implementation below:
const obj = {}; // Empty object const keys = Object.keys(obj); // [] if(keys.length==0){ console.log('Object is empty'); }else{ console.log('Object is not empty'); }
If the object isn’t empty, the Object.keys()
method returns an array consisting of all the keys:
const obj = { name: 'John', age: 25 }; const keys = Object.keys(obj); // Get the keys array console.log(keys) // ["name", "age"]
An alternative approach could be to stringify the object and check if the result is equal to '{}'
string. If it is so, then the object is empty otherwise it’s not.
See the implementation below:
const obj = {}; // Empty object if(JSON.stringify(obj)==='{}'){ console.log('Object is empty'); }else{ console.log('Object is not empty'); }