You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-hook-form筛选数组,为何返回国家对象而非嵌套城市数组?

问题:使用filter获取匹配国家的城市数组却返回国家对象?

问题场景

我有如下包含国家及嵌套城市的数组:

[
  {
    "countryCode": "HU",
    "countryName": "HUNGARY",
    "cities": [
      {
        "cityCode": "BUD",
        "cityName": "BUDAPEST"
      },
      {
        "cityCode": "DEB",
        "cityName": "DEBRECEN"
      },
      {
        "cityCode": "ZLG",
        "cityName": "ZALAEGERSZEG MA BUS STATION"
      }
    ]
  },
  {
    "countryCode": "GB",
    "countryName": "UNITED KINGDOM",
    "cities": [
      {
        "cityCode": "ABZ",
        "cityName": "ABERDEEN"
      },
      {
        "cityCode": "ACI",
        "cityName": "ALDERNEY"
      },
      {
        "cityCode": "ADX",
        "cityName": "ST ANDREWS"
      }
    ]
  }
]

用react-hook-form监听国家选择:

const countryName = form.watch('countryName');

尝试用filter获取匹配国家的城市数组:

const cityOptions = countryOptions.filter(country => {
   console.log(country.countryName, countryName); // 输出: HUGNARY HUNGARY
   return country.countryName === countryName && country.cities;
})

控制台确认countryName匹配,但返回的是匈牙利国家对象而非内部的cities数组:

[
    {
        "countryCode": "HU",
        "countryName": "HUNGARY",
        "cities": [
            {
                "cityCode": "BUD",
                "cityName": "BUDAPEST"
            },
            {
                "cityCode": "DEB",
                "cityName": "DEBRECEN"
            },
            {
                "cityCode": "ZLG",
                "cityName": "ZALAEGERSZEG MA BUS STATION"
            }
        ]
    }
]

问题原因

filter方法的作用是筛选出数组中符合条件的原元素,返回由这些元素组成的新数组,它不会自动提取元素的某个属性。你当前的逻辑只是筛选出匹配的国家对象,并没有对结果做进一步的属性提取,所以返回的是国家对象数组,而非其内部的cities数组。

另外注意控制台输出的拼写:HUGNARY是笔误,应该是HUNGARY,虽然你说匹配上了,但后续要避免这类拼写错误导致的匹配失败。

解决方案

方法1:用find直接定位国家再取cities(更高效)

因为国家名称是唯一的,用find找到第一个匹配的国家对象,再提取其cities属性:

const selectedCountry = countryOptions.find(country => country.countryName === countryName);
const cityOptions = selectedCountry ? selectedCountry.cities : [];

方法2:用filter+flatMap提取cities

如果坚持用filter,需要在筛选后提取每个国家的cities并展开成一维数组:

const cityOptions = countryOptions
  .filter(country => country.countryName === countryName && country.cities)
  .flatMap(country => country.cities);

flatMap会把每个国家的cities数组展开,最终得到所有匹配国家的城市列表。

内容的提问来源于stack exchange,提问作者David Kiss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:37:03