
Typescript dictionary class: Learn with examples.
In this Blog Post, Learn How to iterate a dictionary in typescript with examples.
Dictionary is a type of data structure with unordered list data, that contains key and value values. It is the same as map type in typescript.
Dictionary object declare in may ways, Check about declare dictionary in typescript
Let’s create a Dictionary type interface in typescript
interface Dictionary<T> {
[Key: string]: T;
}
Initialize the Dictionary object with data
let emps: Dictionary<string> = {};
emps["name"] = "john";
emps["id"] = "1";
emps["salary"] = "5000";
Let’s see multiple ways to iterate the dictionary object
for-in loop
Typescript have multiple loop syntax to iterate enumerable objects.
One way is to use for in loop for retrieving keys and values from a dictionary.
for (let key in emps) {
let value = emps[key];
console.log(key + " : " + value)
}
Output:
"name : john"
"id : 1"
"salary : 5000"
for-of loop
Another way, use the for-of loop for retrieving keys and values from a dictionary.
for (const key of Object.keys(emps)) {
let value = emps[key];
console.log(key + " : " + value)
}
Similarly, you rewrite the above with key and value in for of loop syntax.
for (let [key, value] of Object.entries(emps)) {
console.log(key + " : " + value)
}
foreach loop
- using ES6
object have
keys
method introduced in theES6
version.
configure lib in tsconfig.json Tt make this works in typescript.
"lib": [
"es2016",
"dom"
]
Object. keys
returns the array of keys from a dictionary.
use forEach
syntax. to iterate the keys and retrieve the value for the given key.
Finally, Print it to the console.
Object.keys(emps).forEach(key => {
let value = emps[key];
console.log(key + " : " + value)
});
- In ES7 Version
Another way to use the
ES7
version
the object has theentries()
method introduced in the ES2017 version.
configure lib in tsconfig.json to make this works in typescript
"lib": [
"es2017",
"dom"
]
Object. entries
returns the array of key and value pairs from a dictionary.
use forEach
syntax, to iterate the keys and values.
Finally, Print it to the console.
Object.entries(emps).forEach(
([key, value]) => console.log(key + " : " + value)
);
Conclusion
Learned typescript dictionaries loop examples to get key and value objects in multiple ways.