Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  173] [ 3]  / answers: 1 / hits: 33675  / 12 Years ago, mon, march 19, 2012, 12:00:00

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?


More From » json

 Answers
40

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++)
alert(object[keysbyindex[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) {
alert(object[key])
counter++;
}


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


[#86750] Saturday, March 17, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
simone

Total Points: 558
Total Questions: 96
Total Answers: 99

Location: British Indian Ocean Territory
Member since Tue, Feb 22, 2022
2 Years ago
;