Stefan Stefan - 1 year ago 58
JSON Question

How to access fields in JSON object by index

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

. 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?

Answer Source

A JSON Object is more like a key-value-map; so, yes, it is unsorted. The only way to get around is the index->property name map you've already mentioned:

var keysbyindex = Object.keys(object);
for (var i=0; i<keysbyindex.length; i++)

But why would you need these indexes? A unsorted map also has no length property, as an Array had. Why don't you use the for-in-loop

var counter = 0; // if you need it
for (var key in object) {

? If you have a parsed JSON object, i.e. a plain JS Object, you won't have to worry about enumerable prototype properties.