简体   繁体   中英

How do I get an array of countries from this JSON object?

[
 {
   "ISO 3166 Country Code": "AD",
   "Country": "Andorra",
   "Latitude": 42.5,
   "Longitude": 1.5
 },
 {
   "ISO 3166 Country Code": "AE",
   "Country": "United Arab Emirates",
   "Latitude": 24,
   "Longitude": 54
 },
 {
   "ISO 3166 Country Code": "AF",
   "Country": "Afghanistan",
   "Latitude": 33,
   "Longitude": 65
 },
 {
   "ISO 3166 Country Code": "AG",
   "Country": "Antigua and Barbuda",
   "Latitude": 17.05,
   "Longitude": -61.8
 }
]

Do this:

var countries = [];

fetch("url.json").then(response => {
    return response.json();
}).then(data => {
    for (var i = 0; i < data.length; i++) {
        countries.push(data[i].Country);
    }
});

Use Array.map

 let arr = [{"ISO 3166 Country Code":"AD","Country":"Andorra","Latitude":42.5,"Longitude":1.5},{"ISO 3166 Country Code":"AE","Country":"United Arab Emirates","Latitude":24,"Longitude":54},{"ISO 3166 Country Code":"AF","Country":"Afghanistan","Latitude":33,"Longitude":65},{"ISO 3166 Country Code":"AG","Country":"Antigua and Barbuda","Latitude":17.05,"Longitude":-61.8}]; let countries = arr.map(v => v.Country); console.log(countries); 

var arr = [...]// posted in question
var countries = arr.map(function(element) { return element['Country'] })

The easiest and most concise way to do it would be with array.map . However, if you consider performance to be an issue, using a for loop could be a magnitude of ten faster. See the following link for more information about performance https://hackernoon.com/javascript-performance-test-for-vs-for-each-vs-map-reduce-filter-find-32c1113f19d7

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM