Sergio del Amo
Sergio del Amo

Reputation: 78116

How to check if a JSON response element is an array?

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?

Upvotes: 38

Views: 72009

Answers (3)

sonichy
sonichy

Reputation: 1478

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

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

Upvotes: 30

Quentin
Quentin

Reputation: 944011

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

Upvotes: 5

James
James

Reputation: 111950

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
    }
}

Upvotes: 64

Related Questions