Is there an easier way to see if an object is empty?

Of course I can do:

var obj = {};
if(Object.keys(obj).length == 0)

but I was curious if there is a way to say:

var obj = {};
if(obj.hasKeys())

or even:

//already tested, and this doesnt work.  its true because it *is* something.
var obj = {};
if(!obj)
+3
source share
5 answers
function hasKeys(o) {
    for (var name in o)
        if (o.hasOwnProperty(name))
            return true;
    return false;
}
+4
source

This will detect enumerable properties, and inherit fromObject.prototype , as your example:

Object.defineProperty(Object.prototype, "hasKeys", {
    configurable: true,
    value: function() {
        for (var _ in this) return true;
        return false;
    }
});

To detect non-enumerable properties, you will need to use Object.getOwnPropertyNames.

+3
source

, :

function isObjectEmpty(object) {
 for(var i in object) 
  if(object.hasOwnProperty(i))
    return false;

  return true;
}

, , - , .

+1

, JS :

if( Object.keys({})[0] ) alert("non-empty object");

- , , - , () . ex: {"": 0}...

: , .

+1

. ...

Object.prototype.hasKeys = function () {
  return Object.keys(this).length > 0
}

... ; JavaScript - . , is_empty(obj), , - , Underscore isEmpty jQuery isEmptyObject, .

0

All Articles