Advertisement
Advertisement


How do I test for an empty JavaScript object?


Question

After an AJAX request, sometimes my application may return an empty object, like:

var a = {};

How can I check whether that's the case?

2020/01/17
1
3247
1/17/2020 1:22:02 PM

Accepted Answer

ECMA 5+:

// because Object.keys(new Date()).length === 0;
// we have to do some additional 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:

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
2020/03/08
5670
3/8/2020 2:24:41 PM

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;
}

If ECMAScript 5 support is available, you can use Object.keys() instead:

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}
2014/08/29

For those of you who have the same problem but use jQuery, you can use jQuery.isEmptyObject.


This is my preferred solution:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
2014/07/12

You can use Underscore.js.

_.isEmpty({}); // true
2016/01/21

if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

see http://bencollier.net/2011/04/javascript-is-an-object-empty/

2013/11/06

Source: https://stackoverflow.com/questions/679915
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]