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($('
}
}
addObjectToList(your_object);
You could also use:var obj = {};var isEmpty = Object.keys(obj).length === 0;//orisEmpty = Object.getOwnPropertyNames(obj).length === 0;