Home > OS >  typescript get a value from a json object map using a variable key
typescript get a value from a json object map using a variable key

Time:12-28

I am having trouble trying to get a a 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]);

CodePudding user response:

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

  • Related