Fallenreaper
Fallenreaper

Reputation: 10682

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

Sure 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)

Upvotes: 3

Views: 585

Answers (5)

dandavis
dandavis

Reputation: 16726

without making you're own function, you can at least use a shorter syntax thanks to JS's ability to coerce:

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

the only caveat with this dead-simple approach is if you actually want to detect inherited or computed properties, or if you somehow have an object with a blank key, which is (hopefully) very uncommon. ex: {"":0}...

note: I altered my orig answer to make it slightly more readable.

Upvotes: 1

Bergi
Bergi

Reputation: 664165

This will detect enumerable properties, and is inherited from the Object.prototype like 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 would have to use Object.getOwnPropertyNames.

Upvotes: 3

Stu1986C
Stu1986C

Reputation: 1510

May be best to create a function and call it when you need it:

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

  return true;
}

At least using this method name you, and your fellow coders, can clearly see what you're testing the object for.

Upvotes: 1

squid314
squid314

Reputation: 1395

function hasKeys(o) {
    for (var name in o)
        if (o.hasOwnProperty(name))
            return true;
    return false;
}

Upvotes: 4

user229044
user229044

Reputation: 239220

No. You could make it work...

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

... but you shouldn't; modifying prototypes of built-in classes in JavaScript is a pretty bad idea. You'd be better off just writing a utility method like is_empty(obj), or using a library that already provides something like that, like Underscore's isEmpty or jQuery's isEmptyObject for example.

Upvotes: 0

Related Questions