检查值是否在嵌套数组内的更好方法 - Javascript



我正在使用Google Places API。我注意到当我进入机构时并不总是有邮政编码、国家、城市,如果他们这样做,它们并不总是在 address_components 数组内的同一索引中。

现在,我正在尝试查找它是否具有上面列出的任何内容,以及它是否确实返回了该值。有没有更好的方法来实现这一目标:

getPlaceTypeValue(addressComponents: Places[], type: string): string {
let value = null;
for (const [i] of addressComponents.entries()) {
if (addressComponents[i].types.includes(type)) {
value = addressComponents[i].long_name;
break;
}
}
return value;
} 
console.log(this.placesService.getPlaceTypeValue(
address.address_components, 'postal_code'));
//Returns 77500

数据

[
{
"long_name": "Hotel Zone",
"short_name": "Hotel Zone",
"types": [
"sublocality_level_1",
"sublocality",
"political"
]
},
{
"long_name": "Kukulcan Boulevard",
"short_name": "Kukulcan Boulevard",
"types": [
"neighborhood",
"political"
]
},
{
"long_name": "Cancún",
"short_name": "Cancún",
"types": [
"locality",
"political"
]
},
{
"long_name": "Quintana Roo",
"short_name": "Q.R.",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "Mexico",
"short_name": "MX",
"types": [
"country",
"political"
]
},
{
"long_name": "77500",
"short_name": "77500",
"types": [
"postal_code"
]
}
]

首先,我会改变这个:

for (const [i] of addressComponents.entries()) {
if (addressComponents[i].types.includes(type)) {

对此:

for (const {types} of addressComponents) {
if (types.includes(type)) {

或者,如果您喜欢功能更强大的方法,请在单行return语句中使用Array#find

return (addressComponents.find(({types}) => types.includes(type)) || {}).long_name || null;

仅当返回值undefined不适合您时才需要|| null部分。

速度

如果你的问题中"更好"意味着"更快",那么去老式的for循环:

for (let i = 0, len = addressComponents.length; i < len; i++) {
if (addressComponents[i].types.includes(type)) {

相关内容

  • 没有找到相关文章

最新更新