38

I am receiving the next JSON response

    {
    "timetables":[
        {"id":87,"content":"B","language":"English","code":"en"},                                                
        {"id":87,"content":"a","language":"Castellano","code":"es"}],
    "id":6,
    "address":"C/Maestro José"
    }

I would like to achieve the next pseudo code functionality

for(var i in json) {            
    if(json[i]  is Array) {
    // Iterate the array and do stuff
    } else {
    // Do another thing
    }
}

Any idea?

3 Answers 3

64

There are other methods but, to my knowledge, this is the most reliable:

function isArray(what) {
    return Object.prototype.toString.call(what) === '[object Array]';
}

So, to apply it to your code:

for(var i in json) {                    
    if(isArray(json[i])) {
    // Iterate the array and do stuff
    } else {
    // Do another thing
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

There is now a native function in JavaScript that will do this (Array.isArray(obj)), though older browsers will still need to rely on this as a polyfill.
30

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

if(Array.isArray(json[i])){
    // true
    ...
}

Comments

5
function isArray(ob) {
  return ob.constructor === Array;
}

1 Comment

This will work in most situations but it will fail when you're testing an array from a different window/frame since the constructor will be different.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.