In this tutorial explain of check object is empty in javascript. You can check your javascript object is empty or not, we need to check javascript object is empty, null or undefined etc.
Check object is empty in javascript using method like ‘Object.keys()’ and ‘JSON.stringify()’. You can check JSON object is empty or not in javascript. The number of keys or properties of an object can be checked. If the object key count is 0, the object is empty, otherwise object is not empty.
- Using Object.keys() method
- Using JSON.stringify() method
- Using Object.entries() method
- Using Object.values() method
- Using hasOwnProperty() method
you can use various methods. let’s see example below.
1. Check object is empty using 'Object.keys()' :
The Object.keys() method returns an array of given object’s own property names. You can check the length of this array to determine the object is empty or not.
function isEmptyObj(obj) {
return Object.keys(obj).length === 0;
}
const myNewObj = {};
console.log(isEmptyObj(myNewObj));
Explanation:
- Object.keys(obj) return an array of keys. If Obj has no properties, the array will be empty.
- We check if Object.keys(obj).length is 0 to confirm the object is empty.
2. Check object is empty using 'JSON.stringify()':
You can also use of the the JSON.stingify() method, used to convert a javascript value to a JSON string. This means it will convert your object value to a string of the object. let’ see below example. You can use below example to check object is empty or not.
function isEmptyObj(obj1) {
return JSON.stringify(obj1) === '{}';
}
const myNewObj = {};
console.log(isEmptyObj(myNewObj));
3. Check object is empty using 'Object.entries()':
This method returns an array of a given object’s own string-keyed [key, value] pairs. You can check the length of this array to determine object is empty or not.
function isEmptyObj(obj1) {
return Object.entries(obj1).length === 0;
}
const obj1 = {};
console.log(isEmptyObj(obj1));
4. Check object is empty in javascript using Object.values() method
This method like the .keys() method, if an object has no values with it undefined and null means object is empty. can use the .values() method of if object empty or not. let’ see below example.
function isEmptyObj(obj1) {
return Object.values(obj1).length === 0 && obj.constructor === Object;
}
var obj1 = {};
console.log(isEmptyObj(Obj1));
5. Check object is empty using object properties with for...in
The for…in statement will loop check the enumerable property of the object. You can see below example.
function isEmptyObj(onj) {
for(var props in objNew) {
if(objNew.hasOwnProperty(props)) {
return false;
}
return true;
}
}
In above example, we will loop through object properties and if an object has at least one property, then return false and object doesn’t have any property then return true.
I hope this tutorial help you.