我从googlemaps API获得了这样的数组:
"result" : {
"address_components" : [
{
"long_name" : "Blasieholmsgatan",
"short_name" : "Blasieholmsgatan",
"types" : [ "route" ]
},
{
"long_name" : "Norrmalm",
"short_name" : "Norrmalm",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Stockholm",
"short_name" : "Stockholm",
"types" : [ "postal_town" ]
},
{
"long_name" : "Stockholms län",
"short_name" : "Stockholms län",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Sverige",
"short_name" : "SE",
"types" : [ "country", "political" ]
},
{
"long_name" : "111 48",
"short_name" : "111 48",
"types" : [ "postal_code" ]
}
],
"adr_address" : "\u003cspan class=\"street-address\"\u003eBlasieholmsgatan\u003c/span\u003e, \u003cspan class=\"postal-code\"\u003e111 48\u003c/span\u003e \u003cspan class=\"locality\"\u003eStockholm\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eSverige\u003c/span\u003e",
"formatted_address" : "Blasieholmsgatan, 111 48 Stockholm, Sverige",
"geometry" : {
"location" : {
"lat" : 59.3300268,
"lng" : 18.0767623
},
"viewport" : {
"northeast" : {
"lat" : 59.3313757802915,
"lng" : 18.07811128029151
},
"southwest" : {
"lat" : 59.32867781970849,
"lng" : 18.0754133197085
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "13f208be3747ee13670af15b7a3aa838ef511659",
"name" : "Blasieholmsgatan",
"place_id" : "ChIJ1UFulFmdX0YRBL2RMqWlm-8",
"reference" : "CmRbAAAAcNWeXrQZ7dVVRpjNHcDUsgCrzIwy6au7GoIoEylqnOpAk1RitdeEq89rYUd9SRtXiZWK6gC6c46bXiV4k5rDljoQ6_Tk2UKBcZshv3LcwRJbnXJqPiMJwE_qxrxquRH7EhAaye_BQjF-Yff_yulQotQZGhTn5DDbhets_MnS-wbn5gl7EPQx0A",
"scope" : "GOOGLE",
"types" : [ "route" ],
"url" : "https://maps.google.com/?q=Blasieholmsgatan,+111+48+Stockholm,+Sverige&ftid=0x465f9d59946e41d5:0xef9ba5a53291bd04",
"utc_offset" : 60,
"vicinity" : "Norrmalm"
}
我想要的是long_name
为type
的对象中的值"postal_town"
。
我试图这样做:
method(place){
place.address_components.forEach(m => {
if (m.types == "postal_town"){
return m.long_name;
}
});
return "I fucked up!";
}
是否存在问题,因为类型是数组还是我做错了?它应该能够找到类型,对吧?
答案 0 :(得分:0)
在:
"address_components" : [
...
{
"long_name" : "Stockholm",
"short_name" : "Stockholm",
"types" : [ "postal_town" ]
},
types
是一个数组,要在其中查找值,请使用types.includes(value)
,而不是==
。
此外,在.forEach()
中返回并不符合您的想法。由于您要在address_components
数组中查找值,因此最好使用.find()
代替.forEach()
:
method(place) {
let placeFound = place.address_components.find(m => m.types.includes("postal_town"));
if (placeFound) {
return placeFound.long_name;
}
return "I fucked up!";
}