簡體   English   中英

typescript 使用變量鍵從 json object map 獲取值

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

我在嘗試從 map 中獲取 aa 值時遇到問題,我們在其中對密鑰進行了可變化。

讓我展示一下我想要達到的目標。 假設我有一個變量 map,其值為:

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

我有一個用戶輸入變量國家

let country = "Argentina";

我想使用下面的兩個來使用用戶輸入的鍵值從 map 中獲取值。

console.log(map[$country]);

做你想做的事情的幾種方法(可能還有更多):

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]);

游樂場鏈接

另一種方法是為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]);

游樂場鏈接2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM