gpt4 book ai didi

javascript - 检查值是否位于嵌套数组内部的更好方法 - Javascript

转载 作者:行者123 更新时间:2023-12-01 00:39:50 25 4
gpt4 key购买 nike

我正在使用 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)) {

关于javascript - 检查值是否位于嵌套数组内部的更好方法 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57799692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com