Checking if an object is empty in EcmaScript5 / Javascript

I was getting a JSON response from a server request that can contain just an empty value (this is, nothing, nothing de nothing that we Spaniards say). On checking if the object had anything within I did this which seemed to work… for a while:

var d = response.data;
var person = new Person(d);

/**************/
// inside Person constructor:
if (d) {
   this.Id = d.Id;
   this.Name = d.Name;
   ...
}
...

And that worked quite fine, as sometimes I want to instantiate a Person object without giving it any data, that’s a null or “undefined” and checking if (d) exists just works. But what if d does exist but it’s empty? Coming from the response I have “something”, an empty something, it has no properties, no value, nothing de nothing. It just failed on trying to access the object properties.

After looking here and there, it looks like the best approach I could come with was to create my own custom “isEmpty” method, which I saved on an ecmaScriptExtensions file:

function isEmpty(obj) {
    if (obj == undefined) return true;
    return Object.keys(obj).length === 0;
}

And that seems to work perfectly, now if I check if an object has anything it works:

var d = response.data;
var person = new Person(d);

/**************/
// inside Person constructor:
if (isEmpty(d)) {
   this.Id = d.Id;
   this.Name = d.Name;
   ...
}
...

Leave a Reply

Close Bitnami banner
Bitnami