Wednesday, February 8, 2012

Daily JavaScript: empty objects

How do you test whether a JavaScript object is empty?
The short answer (if you're using JQuery) is:
$.isEmptyObject(obj)


The longer answer is, you loop through its properties. This is the method JQuery is using.

for(var prop in obj) {
// it is not empty if this hits
}


The even longer answer is, you loop through its properties and check that they really belong to it. Properties added to the prototype will come up in this loop, and you might not want to count those.

for(var prop in obj) {
if (obj.hasOwnProperty(prop) {
// it is not empty if this hits
}
}


The loop variable there (prop) is a string which is the property name. Here's a handy fiddle to insert the results of this into an unordered list:
 
your_object = {"armadillos":"are brown","carrots":"are fun too"};

function addObjectToList(my_object){
for(var property in my_object) {
$("ul").append($('<li>'+property+': '+my_object[property]+'</li>'));
}
}

addObjectToList(your_object);

1 comment:

  1. You could also use:

    var obj = {};
    var isEmpty = Object.keys(obj).length === 0;
    //or
    isEmpty = Object.getOwnPropertyNames(obj).length === 0;

    ReplyDelete