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?
Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .
JSON can be either an array or an object.
You can check the character at the first position of the String (after trimming away whitespace, as it is allowed in valid JSON). If it is a { , you are dealing with a JSONObject , if it is a [ , you are dealing with a JSONArray .
The Array. isArray() method checks whether the passed variable is an Array object. It returns a true boolean value if the variable is an array and false if it is not.
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 } }
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