简体   繁体   中英

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.

Let me show what I am trying to achieve. lets say I have a variable map with the values:

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.

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

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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