这是一个脑筋急转弯,所以我使用了地方API(使用插件来实现ember.js,所以我不能真正控制版本,除非我想自己写)并且它返回我看起来像这样的数据
{
"address_components": [
{
"long_name": "1235",
"short_name": "1235",
"types": [
"street_number"
]
},
{
"long_name": "Long Point Road",
"short_name": "Long Point Rd",
"types": [
"route"
]
},
{
"long_name": "Mount Pleasant",
"short_name": "Mt Pleasant",
"types": [
"locality",
"political"
]
},
{
"long_name": "Charleston County",
"short_name": "Charleston County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "South Carolina",
"short_name": "SC",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "29464",
"short_name": "29464",
"types": [
"postal_code"
]
},
{
"long_name": "9020",
"short_name": "9020",
"types": [
"postal_code_suffix"
]
}
],
"adr_address": "<span class=\"street-address\">1235 Long Point Rd</span>, <span class=\"locality\">Mt Pleasant</span>, <span class=\"region\">SC</span> <span class=\"postal-code\">29464-9020</span>, <span class=\"country-name\">USA</span>",
"formatted_address": "1235 Long Point Rd, Mt Pleasant, SC 29464, USA",
"geometry": {
"location": {
"lat": 32.8570647,
"lng": -79.8224902
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id": "f3d33a1a65adc47f7fcf927bb7b18ea91a59fb81",
"name": "1235 Long Point Rd",
"place_id": "ChIJkVjE8_5t_ogRvHeqOGZ6cB0",
"reference": "CpQBjAAAAJEVbHvc6lTEXUvlKHc-wTI3f8g8U6W7i6oARvPyP_2TWTNE7IJQQHTABvbxTtMK6cFxRaksi2xaT7lcQiRB-nv7co7BVzfUMrwqr0YFQZvbLH_OGflPlO---vX4GPTQlDnFinnnixHW7LcRGbPJ4jfgnQ3HnURUCUmCa0WrLTIxiuqEwzIljAGv9K_iUMU9nBIQE57UebJ0CfCs9y0MBBvGeRoUUovGUbFYmgCnPOKVlXhrLQaE5uY",
"scope": "GOOGLE",
"types": [
"street_address"
],
"url": "https://maps.google.com/?q=1235+Long+Point+Rd,+Mt+Pleasant,+SC+29464,+USA&ftid=0x88fe6dfef3c45891:0x1d707a6638aa77bc",
"vicinity": "Mount Pleasant",
"html_attributions": []
}
因此,在对象的address_components
部分,您可以看到每个对象都有一个types
键,其值与其属于哪种类型相关,例如street_number
或{{1} }。我想要做的是获取route
包含short_name
或long_name
的对象的type
(或street_number
),依此类推,等等能够将这些设置为变量或以其他方式使用它们。
我已经尝试了几个地址并且它们以大致相同的顺序返回它们,但是有时在该数组中有一个或多一个项目因此它并不总是返回相同数量的项目完全相同的顺序。因此,不要试图查看索引,并希望这是正确的价值,我希望我能根据route
所说的内容获取这些值。
我正在使用ember.js,所以如果有一个计算属性的方式可能会这样做很酷,但我打开使用javascript / jQuery函数来做到这一点。
答案 0 :(得分:3)
你可以写一个函数
function getAdress(what, obj) {
return obj.address_components.filter(function(item) {
return item.types.indexOf(what) !== -1;
}).shift();
}
并在需要查找内容时使用
getAdress('street_number', obj).short_name