PDA

View Full Version : Resolved Shortest way to check if object is populated?



jlizarraga
01-20-2009, 07:29 PM
Hi all,

What is the shortest way to check if an object is empty or not? With an array, I just check that the length is greater than 0. Is there an equally simple way to check an object?

Thanks!

Twey
01-20-2009, 07:42 PM
That question doesn't really make sense. No object (other than null) is truly 'empty': there are properties defined on Object.prototype.

jlizarraga
01-20-2009, 08:07 PM
I found the answer:

if (!Object.prototype.isEmpty)
{
Object.prototype.isEmpty = function() {
for (var prop in this) {
if (this.hasOwnProperty(prop)) return false;
}
return true;
};
}

I am dealing with some JSON data where this is the only way I have of knowing whether or not to dive into the target object.

Twey
01-20-2009, 08:13 PM
Why don't you just start the loop anyway? If there are no properties on the object, it won't do anything (but do make sure to check with hasOwnProperty()).

jlizarraga
01-20-2009, 09:48 PM
Yeah this probably seems retarded without some backstory, lol.

I do car websites (for my 9-5 anyway) and so I'm dealing with vehicle data that a web service spits out as a JSON object. When it comes time to display a vehicle's standard equipment, the various types of equipment are all objects.

But sometimes a vehicle won't have a certain type of equipment, and rather than omitting the object for that type, it just comes back as a blank/empty. So I can't check for defined-ness.

As for why I don't just start the loop anyway, I have to know how many key/value pairs are in the object before I use a loop to do something with each pair (which the server doesn't tell me). The data is going into a fixed number of columns (each column being part of the same overall list) but it is sometimes alphabetical so I use the number of pairs divided by the number of columns to figure out how many pairs to put in each column before moving on to the next column.

So I first check to make sure the object has key/value pairs in it (the part I came for help on), then use the magic pair-per-column number to iterate through them once again, this time sending the data to the columns.