How to access fields in JSON object by index

Posted by Stefan on Stack Overflow See other posts from Stack Overflow or by Stefan
Published on 2012-03-19T09:58:50Z Indexed on 2012/03/19 10:03 UTC
Read the original article Hit count: 274

Filed under:
|

I know this isn't the best way to do it, but I have no other choice :(

I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object:

(for (var key in p) { 
  if (p.hasOwnProperty(key)) { 
    alert(key + " -> " + p[key]); 
  } 
} 

(Soruce : Loop through Json object).

However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname.

As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list?

Regards, Stefan

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about JSON