我正在尝试根据其中一个子元素的值在数组中选择一个元素。
使用从 Google Maps API 地理编码请求返回的结果作为示例,我们有一个形式的数组:
{
"address_components": [
{
"long_name": "Renshaw St",
"short_name": "Renshaw St",
"types": [
"route"
]
},
{
"long_name": "Eccles",
"short_name": "Eccles",
"types": [
"locality",
"political"
]
},
{
"long_name": "Greater Manchester",
"short_name": "Gt Man",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "United Kingdom",
"short_name": "GB",
"types": [
"country",
"political"
]
},
{
"long_name": "M30 0PQ",
"short_name": "M30 0PQ",
"types": [
"postal_code"
]
},
{
"long_name": "Manchester",
"short_name": "Manchester",
"types": [
"postal_town"
]
}
],
"formatted_address": "Renshaw St, Eccles, Manchester, Greater Manchester M30 0PQ, UK",
"geometry": {
"bounds": {
"northeast": {
"lat": 53.48266090000001,
"lng": -2.35206530
},
"southwest": {
"lat": 53.48128999999999,
"lng": -2.35324410
}
},
"location": {
"lat": 53.4822450,
"lng": -2.35294730
},
"location_type": "GEOMETRIC_CENTER",
"viewport": {
"northeast": {
"lat": 53.48332443029150,
"lng": -2.351305719708498
},
"southwest": {
"lat": 53.48062646970850,
"lng": -2.354003680291502
}
}
},
"types": [
"route"
]
}
我想选择address_component->long_name
元素type
等于我指定的值的那个。
我编写了以下代码,将上述内容array
和 akey
作为参数,并且似乎运行良好:
function getAddressComponent(key, result) {
var rtn;
$.each(result,function(index,value){
if( result[index].types[0] == key ) rtn = result[index].long_name;
});
return rtn;
}
但是想知道是否有人可以提出更好的方法,因为我已经看到它以几种不同的方式完成并希望使用最佳方法。