views:

176

answers:

1

Possible Duplicate:
How do I test for an empty Javascript object from JSON?

Is there an easy way to check if an object has no properties, in Javascript? Or in other words, an easy way to check if a map/associative array is empty? For example, let's say you had the following:

var nothingHere = {};
var somethingHere = {foo: "bar"};

Is there an easy way to tell which one is "empty"? The only thing I can think of is something like this:

function isEmpty(map) {
   var empty = true;

   for(var key in map) {
      empty = false;
      break;
   }

   return empty;
}

Is there a better way (like a native property/function or something)?

+2  A: 

Try this:

function isEmpty(map) {
   for(var key in map) {
      if (map.hasOwnProperty(key)) {
         return false;
   }
   return true;
}

Your solution works, too.... but only if there is no library extending the Object prototype. It or may not be good enough.

chryss
Thanks!........
Vivin Paliath
The `hasOwnProperty` call is pretty vital here if any libraries are messing around with the `Object` prototype. +1
CD Sanchez
Thanks. I put the remark in the solution -- I had adopted the hasOwnPrototype call for a while and wasn't even thinking about it any longer.
chryss