views:

560

answers:

2

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?

+7  A: 

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
    }
}
J-P
+1  A: 
function isArray(ob) {
  return ob.constructor === Array;
}
David Dorward
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.
J-P