Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 849
akshat Avatar asked Oct 20 '08 15:10

akshat


People also ask

How do you check if an object is an array or not in JavaScript?

The isArray() method returns true if an object is an array, otherwise false .

How can you tell if an object is an array or an array?

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 .

Is JavaScript object hash?

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.

How do you check if an element is in an array?

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.


2 Answers

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){ } 
like image 137
pawel Avatar answered Sep 30 '22 18:09

pawel


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 } 
like image 33
Borgar Avatar answered Sep 30 '22 20:09

Borgar