I am having trouble parsing a JSON Object with an Array and get the value based on the Key. I do this in one of my android application. I am planning to port the app to web application. In android I do something like this:
Lets say my json is like this:
{"radios":[{"name":"radio1","url":"url1"},{"name":"radio2","url":"url2"}, {"name":"radio3","url":"url3"}] }
My code looks like this in Android:
JSONArray radioListArray = jsonObject.getJSONArray("radios");
ArrayList<String> radioUrlColl = new ArrayList<String>();
for(int i=0; i<radioListArray.length(); i++) {
JSONObject radObject = radioListArray.getJSONObject(i);
radioUrlColl.add(radObject.getString("url"));
}
Intent radioIntent = new Intent(arg0.getContext(), PlayerActivity.class);
String url =radioUrlColl.get(arg2); //I get the URL here
radioIntent.putExtra("radioUrl", url);
Basically, I get the url based on the position of the Clicked item in the list view. Is there a simpler solution where i would pass the key say radio1 and get the corresponding value url1 in Javascript
Is there a simpler solution where i would pass the key say radio1 and get the corresponding value url1 in Javascript
No, with the structure of that data, you still have to loop through the entries looking for the entry with the matching name
property.
So say obj
is the result of calling JSON.parse
on the string containing that JSON text, and targetRadio
is the radio you want. obj.radios
will be the array. So you can use a simple for
loop:
var n;
var url;
for (n = 0; n < obj.radios.length; ++n) {
if (obj.radios[n].name === targetRadio) {
url = obj.radios[n].url;
break;
}
}
Or if you want to rely on ES5's array enhancements (which can be shimmed if necessary), you could use some
:
var url;
obj.radios.some(function(entry) {
if (entry.name === targetRadio) {
url = entry.url;
return true; // To stop looping
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.