41

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)?

Community
  • 1
  • 1
Vivin Paliath
  • 87,975
  • 37
  • 202
  • 284
  • Dupe - http://stackoverflow.com/questions/5223/length-of-javascript-associative-array – Joel Etherton Aug 06 '10 at 19:22
  • @Daniel - thanks for the link to that question. I tried searching on SO but I didn't find anything. Mods - please close this question. Thanks! – Vivin Paliath Aug 06 '10 at 19:22
  • I would go with chryss's solution over yours because of the hasOwnProperty call. If anything extends the Object prototype (something many libraries do), your method will no longer return the correct results as it will read inherited properties. – Cristian Sanchez Aug 06 '10 at 19:36
  • @Daniel yeah, I like it for that reason as well. Prototype seems to pollute the namespace that way. – Vivin Paliath Aug 06 '10 at 19:39

1 Answers1

51

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 may or may not be good enough.

Frazer Kirkman
  • 716
  • 1
  • 10
  • 17
chryss
  • 7,073
  • 36
  • 44
  • The `hasOwnProperty` call is pretty vital here if any libraries are messing around with the `Object` prototype. +1 – Cristian Sanchez Aug 06 '10 at 19:38
  • 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 Aug 06 '10 at 19:41
  • 1
    you ever not even thinking about it any longer and in fact you called it hasOwnPrototype. lol – Zo72 Nov 11 '11 at 22:21