Multiple ways to iterate dictionary in typescript |Dictionary loop Example

Typescript Dictionary Class: Learn with Examples

In this blog post, learn how to iterate through a dictionary in Typescript with examples.

A dictionary is a type of data structure with an unordered list of data that contains key-value pairs. It is similar to the map type in Typescript.

Dictionary objects can be declared in various ways. Check out how to declare dictionary in typescript

Let’s create a Dictionary type interface in Typescript.

interface Dictionary<T> {
  [Key: string]: T;
}

Now, let’s initialize the Dictionary object with data:

let emps: Dictionary<string> = {};
emps["name"] = "John";
emps["id"] = "1";
emps["salary"] = "5000";

Now, let’s explore multiple ways to iterate through the dictionary object.

How to Iterate Through a Dictionary in Typescript Using the for-in Loop

Typescript offers multiple loop syntaxes to iterate through enumerable objects.

  • Using for-in loop One way is to use the for-in loop to retrieve 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"
    
  • Using the for-of Loop Another approach is to use the for-of loop to retrieve keys and values from a dictionary:

    for (const key of Object.keys(emps)) {
      let value = emps[key];
      console.log(key + " : " + value);
    }
    

    Similarly, you can rewrite the above using the key and value syntax in the for-of loop:

    for (let [key, value] of Object.entries(emps)) {
      console.log(key + " : " + value);
    }
    

Iterating Through a Typescript Dictionary Using the forEach Loop

  • using ES6 An object has the keys method introduced in the ES6 version. Configure the lib in tsconfig.json to make this work in Typescript:

    "lib": [
        "es2016",
        "dom"
    ]
    

    Object.keys returns an array of keys from a dictionary. Use the forEach syntax to iterate through 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 is to use the ES7 version. The object has the entries() method introduced in the ES2017 version. Configure lib in tsconfig.json to make this work in Typescript:

    "lib": [
        "es2017",
        "dom"
    ]
    

    Object.entries returns an array of key and value pairs from a dictionary. Use the forEach syntax to iterate through the keys and values. Finally, print it to the console:

    Object.entries(emps).forEach(([key, value]) =>
      console.log(key + " : " + value),
    );
    

Conclusion

You’ve learned Typescript dictionaries loop examples to get key and value objects in multiple ways.