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

如何从对象数组中获取用户所选指定国家的城市?

获取指定国家对应的城市列表

给定的国家-城市数据源:

const countriesData = [
    {
        "id":1,
        "country": "Afghanistan",
        "cities": ["Herat", "Kabul", "Kandahar", "Molah"]
    },
    {
        "id":2,
        "country": "Albania",
        "cities": ["Elbasan", "Petran", "Pogradec"]
    },
    {
        "id":3,
        "country": "Algeria",
        "cities": ["Algiers", "Annaba", "Azazga", "Batna City"]
    }
];

实现方法

用JavaScript的Array.find()方法快速定位匹配的国家对象,再提取对应的城市数组,同时处理未找到目标国家的情况:

function getCitiesByCountry(countryName) {
    // 精准匹配国家名称
    const matchedCountry = countriesData.find(item => item.country === countryName);
    // 存在则返回城市列表,不存在返回空数组
    return matchedCountry ? matchedCountry.cities : [];
}

使用示例

  • 获取指定国家的城市:
const albaniaCities = getCitiesByCountry("Albania");
console.log(albaniaCities); // 输出: ["Elbasan", "Petran", "Pogradec"]
  • 处理不存在的国家:
const invalidCities = getCitiesByCountry("Germany");
console.log(invalidCities); // 输出: []

可选优化:不区分大小写匹配

如果需要兼容用户输入的大小写差异(比如输入"afghanistan"也能匹配),修改判断逻辑即可:

function getCitiesByCountryIgnoreCase(countryName) {
    const lowerCaseName = countryName.toLowerCase();
    const matchedCountry = countriesData.find(item => item.country.toLowerCase() === lowerCaseName);
    return matchedCountry ? matchedCountry.cities : [];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:40:30