简体   繁体   English

typescript 使用变量键从 json object map 获取值

[英]typescript get a value from a json object map using a variable key

I am having trouble trying to get aa value from a map where we variablize the key.我在尝试从 map 中获取 aa 值时遇到问题,我们在其中对密钥进行了可变化。

Let me show what I am trying to achieve.让我展示一下我想要达到的目标。 lets say I have a variable map with the values:假设我有一个变量 map,其值为:

let map = {
 Argentina : "222",
 Brazil : "333",
 Mexico : "444",
};

and I have a user input variable country我有一个用户输入变量国家

let country = "Argentina";

I would like to use the two as follows to use the user inputted key value to get value from the map.我想使用下面的两个来使用用户输入的键值从 map 中获取值。

console.log(map[$country]);

Few ways of doing what you want (probably there is a few more):做你想做的事情的几种方法(可能还有更多):

let map = {
 Argentina : "222",
 Brazil : "333",
 Mexico : "444",
};

let country = "Argentina";
let country2: keyof typeof map = "Argentina";
// let country3: keyof typeof map = "Argentina2"; // Type '"Argentina2"' is not assignable to type '"Argentina" | "Brazil" | "Mexico"'.

console.log(map[country as keyof typeof map]);
console.log((map as any)[country]);
console.log(map[country2]);

Playground link游乐场链接

Another approach would be to specify a type (which will be less strict) for map object explicitly另一种方法是为map object 明确指定一个类型(不太严格)

// let map: {[key: string]: string} = {
let map: {[key: string]: any} = {
 Argentina : "222",
 Brazil : "333",
 Mexico : "444",
};

let country = "Argentina";
console.log(map[country]);

Playgrond link2游乐场链接2

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

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