After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.
You can use Object. values() method to get all the object's values (as an array of object's values) and then check if this array of values contains null or "" values, with the help of _. includes method prvided by lodash library.
The empty object is not undefined. The only falsy values in JS are 0 , false , null , undefined , empty string, and NaN .
ECMA 5+:
// 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
Note, though, that this creates an unnecessary array (the return value of keys
).
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:
jQuery.isEmptyObject({}); // true
lodash:
_.isEmpty({}); // true
Underscore:
_.isEmpty({}); // true
Hoek
Hoek.deepEqual({}, {}); // true
ExtJS
Ext.Object.isEmpty({}); // true
AngularJS (version 1)
angular.equals({}, {}); // true
Ramda
R.isEmpty({}); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With