Reputation: 807
Basically, I have a list of countries with latitude and longitude and want to calculate the distance between two countries. So I put this information in JSON file, which looks like this
[
{
"country":"China",
"latitude":35.0,
"longitude":105.0,
"continent":"Asia"
},
{
"country":"India",
"latitude":20.0,
"longitude":77.0,
"continent":"Asia"
},
...
]
Then I load this file in jQuery: $.getJSON( 'countries.json', function(data){ var json = data; });
And now I would like to get the specific information as easy as json.China.longitude
.
I know it doesn't work like this, but what would be the easiest way?
The calculation of the distance based on GPS coordinates is another thing, but I already found a function for this.
Upvotes: 0
Views: 67
Reputation: 1108
If you want to do that, it would be better for you to change your JSON to be more like, if it's possible of course.
[
{
"China": {
"latitude": 35,
"longitude": 105,
"continent": "Asia"
},
"India": {
"latitude": 20,
"longitude": 77,
"continent": "Asia"
}
}
]
Upvotes: 1
Reputation: 191749
It would be better to update countries.json
to return an object with the country as the key as this will save you some lookup time. Otherwise you have to iterate over the array. You could use native filter
var china = json.filter(function (elem) {
return elem.country == "China";
})[0];
Or you could use something like Underscore.js
Upvotes: 2