繁体   English   中英

尝试将变量与数组中的文件匹配并返回结果

[英]Trying to match a variable to a filed in an array and return a result

我是编程新手,所以如果这是一个愚蠢的问题或之前曾被回答过,请原谅我。

我有一个来自服务器的变量,用于标识城市代码(例如PHO)。 我也有一个对象列表。

Cities [] = [
{label: "Phoenix", code: "PHO"},
{label: "Chicago", code: "CHI"}
];

我需要将从服务器(PHO)获得的城市代码与列表匹配,并返回标签“ Phoenix”。 任何帮助将不胜感激,我只需要朝正确的方向前进。

只需编写一个将输入代码映射到输出标签的函数。

getCity(code: String) {
    for (let city of this.cities) {
        if (city.code == code) {
            return city.label;
        }
    }
    return null;
}

cities定义为

cities = [
    {label: "Phoenix", code: "PHO"},
    {label: "Chicago", code: "CHI"}
];

该函数具有线性时间复杂度O(n) ,如果您使用类似地图的结构,则可以通过将每个代码映射到标签来将其改进为O(1)

您将要使用Array.prototype.find函数在数组中查找匹配的对象(假设只有一个)。

这是一个示例getLabelByCode函数。

 var cities = [ { label: "Phoenix", code: "PHO" }, { label: "Chicago", code: "CHI" } ]; function getLabelByCode(code) { const city = cities.find(c => c.code === code); if (city) { return city.label; } return 'NO LABEL FOUND'; } var result = getLabelByCode("PHO"); console.log('The result is', result); 

或者,如果需要匹配数组中的多个对象,则可以使用Array.prototype.filter

使用ES7

const getCityByCode = code =>
    Object.values(cities).find(city =>
        city.code === code
    )

const phoenix = getCityByCode("PHO")

使用phoenix.label获得label属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM