In javascript how can we identify whether an object is a Hash or an Array?

Modern browsers support the Array.isArray(obj) method.

See MDN for documentation and a polyfill.

= original answer from 2008 =

you can use the constuctor property of your output:

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

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
}

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

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

Tags:

Javascript