How to create key value dictionary in TypeScript

1 Answer

0 votes
let dict : any = {}; // new & empty object
dict["typescript"] = 5;
dict["c"] = 8;
dict["rust"] = 1;
dict["dart"] = 7;

dict.python = 2; // dict.key == dict["key"] 

console.log("key - values:");
for (let key in dict) {
    if (dict.hasOwnProperty(key)) {
        console.log(key + ' - ' + dict[key]);
    }
}

let keys : any = Object.keys(dict);
console.log("\nkey:");
keys.map(function(key : string) {
    console.log(key);
});

let values : any = Object.values(dict);
console.log("\nvalues:");
values.map(function(value : number) {
    console.log(value);
});





/*
run:

"key - values:" 
"typescript - 5" 
"c - 8" 
"rust - 1" 
"dart - 7" 
"python - 2" 

"key:" 
"typescript" 
"c" 
"rust" 
"dart" 
"python" 

"values:" 
5 
8 
1 
7 
2 

*/

 



answered Dec 11, 2022 by avibootz
...