如何从此JSON对象获取国家/地区数组?

时间:2018-11-07 02:41:34

标签: javascript arrays json

[
 {
   "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
 }
]

4 个答案:

答案 0 :(得分:0)

执行以下操作:

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);
    }
});

答案 1 :(得分:0)

使用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);

答案 2 :(得分:0)

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

答案 3 :(得分:0)

最简单,最简洁的方法是使用array.map。但是,如果您认为性能是一个问题,那么使用for循环可能会快10个数量级。 有关性能的更多信息,请参见以下链接 https://hackernoon.com/javascript-performance-test-for-vs-for-each-vs-map-reduce-filter-find-32c1113f19d7