The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?
views:
474answers:
4
+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
2008-10-20 15:32:08
Good answer. You may want to add the every js object can be treated as a hash.
Rontologist
2008-10-20 15:34:33
+6
A:
you can use the constuctor property of your output:
if(output.constructor == Array){
}
else if(output.constructor == Object){
}
pawel
2008-10-20 15:32:16
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
2008-10-20 15:32:45
+1
A:
Did you mean "Object" instead of "Hash"?
>>> var a = [];
>>> var o = {};
>>> a instanceof Array
true
>>> o instanceof Array
false
insin
2008-10-20 15:33:46