-1

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

var test= {};

var incidentReport = {
      "place1": "n/a",
      "place2": "n/a",
      "place3": "n/a",
 }

Above are the two ways my varible is going to look. Ive tryed doing the following code to test if its empty/looks like {}

if(test == "")

and tried

if(test == null)

also tried

if(!test)

Does anyone know where I am going wrong? Just a beginner to JavaScript and JSON. Is what I am doing considered back practice are there better ways to declare this empty?

Thanks for the support

Community
  • 1
  • 1
Lemex
  • 3,646
  • 14
  • 47
  • 82

3 Answers3

2

Use JSON.stringify

var test= {};
if(JSON.stringify(test).length==2)
alert('null')
1
if(test == "")

checks if it is an empty string, so this won't work

if(test == null)

checks if it is null which is "similar" to undefined - this isn't the case

if(!test)

checks if it is a falsy value, this in not the case either.

You have to check if there exist child-elements (properties):

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

if ( isEmpty(test) ){...}

The very important point is the .hasOwnProperty() - this checks if it is a real property of the object and not only inherited through the prototype chain.

Christoph
  • 46,101
  • 18
  • 92
  • 121
  • @Somebodyisintrouble both? It explains why his attempts fail and gives a solution. Feel free to upvote me:-D – Christoph Jun 22 '12 at 09:39
0

test here is an object. so you have to check if there are any prioperties/elements int his object. You can try something like below

var test= {};

function isEmptyObject(obj) {
   // This works for arrays too.
   for(var name in obj) {
       return false
   }
   return true
}

alert("is this object empty?" + isEmptyObject(test));​
Eswar Rajesh Pinapala
  • 4,571
  • 4
  • 29
  • 38