You can use the plain vanilla JS Object keys() method to Check empty objects in JavaScript. For older browser support, install the Lodash library and use their “isEmpty” method.
Object.keys(data).length === 0 && data.constructor === Object
//Lodash for Older Browser
_.isEmpty(empty)
OR
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // 👈 null and undefined check
&& Object.keys(obj).length === 0
&& Object.getPrototypeOf(obj) === Object.prototype
Check empty object JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script >
const obj = {};
if (Object.keys(obj).length === 0 && obj.constructor === Object){
console.log("Object is empty", true)
}
</script>
</body>
</html>
Output:
Other options
Pre-ECMA 5:
function isEmpty(obj) {
for(var prop in obj) {
if(Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
jQuery.isEmptyObject({}); // true
_.isEmpty({}); // true
_.isEmpty({}); // true
Hoek.deepEqual({}, {}); // true
Ext.Object.isEmpty({}); // true
angular.equals({}, {}); // true
R.isEmpty({}); // true
Source: stackoverflow.com
Do comment if you have any doubts or suggestions on this Js object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version