Here are some different methods that you could use to check if an object is empty in modern browsers that support the ES5 edition of JavaScript.
1. The Object.keys()
method
The Object.keys()
method returns an array of enumerable property names of a given object. And thus, we can use it to check if an object has any properties by counting the length of this array.
function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
console.log(isEmptyObject({})); // output: true
var bar = {"foo": "1"};
console.log(Object.keys(bar).length); // output: 1
console.log(isEmptyObject(bar)); // output: false
As you can see in the above example, the bar
object has the foo
property attached to it, and thus the bar.keys(obj).length
expression would return a value greater than zero. So the isEmptyObject
function would return FALSE
in this case.
2. The Object.getOwnPropertyNames()
method
The Object.getOwnPropertyNames()
method returns an array of all the properties of a given object. Although it may look identical to the Object.keys()
method, there’s a difference. The Object.getOwnPropertyNames()
method also considers the non-enumerable properties, while the Object.keys()
only considers enumerable properties.
function isEmptyObject(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
console.log(isEmptyObject({})); // output: true
var bar = {"foo": "1"};
console.log(Object.getOwnPropertyNames(bar).length); // output: 1
console.log(isEmptyObject(bar)); // output: false
As you can see, testing emptiness with Object.getOwnPropertyNames()
works similarly to using Object.keys()
.
3. The JSON.stringify
method
The JSON.stringify
method is used to convert a JavaScript object to a JSON string. So we can use it to convert an object to a string, and we can compare the result with {}
to check if the given object is empty.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
console.log(isEmptyObject({})); // output: true
var bar = {"foo":"1"};
console.log(JSON.stringify(bar)); // output: {"foo":"1"}
console.log(isEmptyObject(bar)); // output: false
4. The Object.entries()
method
The Object.entries()
method returns an array of arrays, with each element being an array of key-value pairs of an object’s property.
function isEmptyObject(obj) {
return Object.entries(obj).length === 0;
}
console.log(isEmptyObject({})); // output: true
var bar = {"foo":"1"};
console.log(Object.entries(bar)); // output: [['foo', '1']]
console.log(Object.entries(bar).length); // output: 1
console.log(isEmptyObject(bar)); // output: false
As you can see, the Object.entries()
method converts an object into an array, and we can count the length of that array to check if the object in question is empty.
Source
https://code.tutsplus.com/tutorials/how-to-check-if-an-object-is-empty-in-javascript–cms-37053