The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?
The isArray() method returns true if an object is an array, otherwise false .
isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .
A JavaScript Object is an example of a Hash Table because data is represented a key/value pairs. A hashing function can be used to map the key to an index by taking an input of any size and returning a hash code identifier of a fixed size.
The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With