tags:

views:

474

answers:

4

The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?

+4  A: 

Is object:

function isObject ( obj ) {
   return obj && (typeof obj  === "object");
}

Is array:

function isArray ( obj ) { 
  return isObject(obj) && (obj instanceof Array);
}

Because arrays are objects you'll want to test if a variable is an array first, and then if it is an object:

if (isArray(myObject)) {
   // do stuff for arrays
}
else if (isObject(myObject)) {
   // do stuff for objects
}
Borgar
Good answer. You may want to add the every js object can be treated as a hash.
Rontologist
+6  A: 

you can use the constuctor property of your output:

if(output.constructor == Array){
}
else if(output.constructor == Object){
}
pawel
A: 

Check for "constructor" property on the object. It is Array - it is an array object.


var a = {
 'b':{length:0},
 'c':[1,2]
}

if (a.c.constructor == Array)
   for (var i = 0; i < a.c.length; i++)
      alert(a.c[i]);
else
   for (var s in a.b);
      alert(a.b[s]);

Sergey Ilinsky
+1  A: 

Did you mean "Object" instead of "Hash"?

>>> var a = [];
>>> var o = {};
>>> a instanceof Array
true
>>> o instanceof Array
false
insin