After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // 👈 null and undefined check
&& Object.keys(obj).length === 0 && obj.constructor === Object
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(obj.hasOwnProperty(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
If ECMAScript 5 support is available, you can use Object.keys()
:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
For ES3 and older, there's no easy way to do this. You'll have to loop over the properties explicitly:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
Today 2020.01.17 I perform tests on macOS HighSierra 10.13.6 on Chrome v79.0, Safari v13.0.4 and Firefox v72.0, for chosen solutions.
Conclusions
for-in
(A,J,L,M) are fastestJSON.stringify
(B,K) are slowObject
(N) is slowThere are 15 solutions presented in the snippet below. If you want to run a performance test on your machine click HERE. This link was updated 2021.07.08 but tests oryginaly was performed here - and results in table above came from there (but now it looks like that service not longer works).
var log = (s,f) => console.log(`${s} --> {}:${f({})} {k:2}:${f({k:2})}`);
function A(obj) {
for(var i in obj) return false;
return true;
}
function B(obj) {
return JSON.stringify(obj) === '{}';
}
function C(obj) {
return Object.keys(obj).length === 0;
}
function D(obj) {
return Object.entries(obj).length === 0;
}
function E(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
function F(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
function G(obj) {
return typeof obj === "undefined" || !Boolean(Object.keys(obj)[0]);
}
function H(obj) {
return Object.entries(obj).length === 0 && obj.constructor === Object;
}
function I(obj) {
return Object.values( obj ).every( val => typeof val === "undefined" );
}
function J(obj) {
for (const key in obj) {
if (hasOwnProperty.call(obj, key)) {
return false
}
}
return true;
}
function K(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) == JSON.stringify({});
}
function L(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
function M(obj) {
for (var k in obj)
{
if ( obj.hasOwnProperty(k) )
{
return false;
}
}
return true;
}
function N(obj) {
return Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
Object.getPrototypeOf(obj) === Object.prototype;
}
function O(obj) {
return !(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(obj).length != 0 : (function(){for(var key in obj) break; return (key != null) && (key != undefined);})())
}
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
log('O',O);
If my answer helped you can buy me a coffee
if(Object.getOwnPropertyNames(obj).length === 0){
//is empty
}
see http://bencollier.net/2011/04/javascript-is-an-object-empty/
Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:
function isEmptyObject(obj) {
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
return false;
}
}
return true;
}
I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.
And what I did was, used the following condition, and it worked for me.
var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
//Code here..
}
For not equal to, use this : JSON.stringify(obj) !== '{}'
Check out this JSFiddle
Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.
Tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:
Bottom line performance wise, use:
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
or
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
See detailed testing results and test code at Is object empty?
Just a workaround. Can your server generate some special property in case of no data?
For example:
var a = {empty:true};
Then you can easily check it in your AJAX callback code.
Another way to check it:
if (a.toSource() === "({})") // then 'a' is empty
EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.
I've created a complete function to determine if object is empty.
It uses Object.keys
from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).
/**
* Returns true if specified object has no properties,
* false otherwise.
*
* @param {object} object
* @returns {boolean}
*/
function isObjectEmpty(object)
{
if ('object' !== typeof object) {
throw new Error('Object must be specified.');
}
if (null === object) {
return true;
}
if ('undefined' !== Object.keys) {
// Using ECMAScript 5 feature.
return (0 === Object.keys(object).length);
} else {
// Using legacy compatibility mode.
for (var key in object) {
if (object.hasOwnProperty(key)) {
return false;
}
}
return true;
}
}
Here's the Gist for this code.
And here's the JSFiddle with demonstration and a simple test.
I hope it will help someone. Cheers!
As per the ES2017 specification on Object.entries(), the check is simple using any modern browser--
Object.entries({}).length === 0
I am using this.
function isObjectEmpty(object) {
var isEmpty = true;
for (keys in object) {
isEmpty = false;
break; // exiting since we found that the object is not empty
}
return isEmpty;
}
Eg:
var myObject = {}; // Object is empty
var isEmpty = isObjectEmpty(myObject); // will return true;
// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"};
// check if the object is empty
isEmpty = isObjectEmpty(myObject); // will return false;
Update
OR
you can use the jQuery implementation of isEmptyObject
function isEmptyObject(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.
The script works on ES6.
const isEmpty = (obj) => {
if (obj === null ||
obj === undefined ||
Array.isArray(obj) ||
typeof obj !== 'object'
) {
return true;
}
return Object.getOwnPropertyNames(obj).length === 0;
};
console.clear();
console.log('-----');
console.log(isEmpty('')); // true
console.log(isEmpty(33)); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello')); // true
console.log(isEmpty([1, 2, 3])); // true
console.log(isEmpty({ test: 1 })); // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date())); // true
console.log(isEmpty(Infinity)); // true
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
jQuery have special function isEmptyObject()
for this case:
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
Read more on http://api.jquery.com/jQuery.isEmptyObject/
Under the hood all empty check methods in all libraries use object keys checking logic. Its an odd way to make it understandable, which you can put in a method, Described here.
for(key in obj){
//your work here.
break;
}
Which has evolved in ES5, now put simply you can check the object's keys length, using Object.Keys
method which takes your object as it's parameter:
if(Object.keys(obj).length > 0){
//do your work here
}
Or if you are using Lodash (you must be) then.
_.isEmpty(obj) //==true or false
you can use this simple code that did not use jQuery or other libraries
var a=({});
//check is an empty object
if(JSON.stringify(a)=='{}') {
alert('it is empty');
} else {
alert('it is not empty');
}
JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.
Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.
var a=({});
function isEmptyObject(obj) {
if(typeof obj!='object') {
//it is not object, so is not empty
return false;
} else {
var x,i=0;
for(x in obj) {
i++;
}
if(i>0) {
//this object has some properties or methods
return false;
} else {
//this object has not any property or method
return true;
}
}
}
alert(isEmptyObject(a)); //true is alerted
Best way that I found:
function isEmpty(obj)
{
if (!obj)
{
return true;
}
if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
{
return true;
}
return false;
}
Works for:
t1: {} -> true
t2: {0:1} -: false
t3: [] -> true
t4: [2] -> false
t5: null -> true
t6: undefined -> true
t7: "" -> true
t8: "a" -> false
t9: 0 -> true
t10: 1 -> false
The correct answer is:
const isEmptyObject = obj =>
Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
Object.getPrototypeOf(obj) === Object.prototype;
This checks that:
Object.prototype
.In other words, the object is indistinguishable from one created with {}
.
Caveat! Beware of JSON's limitiations.
javascript:
obj={ f:function(){} };
alert( "Beware!! obj is NOT empty!\n\nobj = { f:function(){} }" +
"\n\nJSON.stringify( obj )\n\nreturns\n\n" +
JSON.stringify( obj ) );
displays
Beware!! obj is NOT empty! obj = { f:function(){} } JSON.stringify( obj ) returns {}
if (Object.keys(obj).length === 0) { // handle empty obj }
– Gabriel Petersson