How to use Object.keys() and forEach() methods In Javascript

In this approach, we use the Object.keys() and forEach() method to iterate over the keys of mapped type record with the generic values. For each key, the associated generic value is retieved and printed.

Syntax:

Object.keys(myObject).forEach(key => console.log(`${key}: ${myObject[key]}`)); 

Example: The below example uses Object.keys() and forEach() methods to iterate through mapped type record with generic values in TypeScript.

Javascript
type obj3 = {
    topic: string;
    difficulty: number;
};
const gfgData: Record<string, obj3> = {
    algorithm: {
        topic: "Algorithms",
        difficulty: 3
    },
    dataStructure: {
        topic: "Data Structures",
        difficulty: 2
    },
    language: {
        topic: "Programming Languages",
        difficulty: 1
    },
};
Object.keys(gfgData).forEach((key) => {
    const data = gfgData[key];
    console.log(`${key}: ${data.topic},
     Difficulty: ${data.difficulty}`);
});

Output:

algorithm: Algorithms, Difficulty: 3
dataStructure: Data Structures, Difficulty: 2
language: Programming Languages, Difficulty: 1

How to Iterate Through Mapped Type Record with Generic Value ?

In TypeScript, we can iterate through the mapped type record with the generic value by extracting the keys and the access its corresponding generic values. This mainly can be done using various approaches like loop, and builtin Object methods. In this article, we will explore three different approaches to iterate through mapped type records with generic values in TypeScript.

These are the following approaches:

Table of Content

  • Using for…in Loop
  • Using Object.entries() method
  • Using Object.keys() and forEach() methods
  • Using Object.getOwnPropertyNames()

Similar Reads

Using for…in Loop

In this approach, we use for…in loop to iterate over the keys of a mapped type record with generic values. This basically, accesses each key by allowing the extraction of the corresponding generic value....

Using Object.entries() method

In this approach, we use Objects.entries() method to iterate through the key-value pairs of the mapped type record with the generic values. the desstruuting of the entires mainly allows direct access to the key and its associated generic value....

Using Object.keys() and forEach() methods

In this approach, we use the Object.keys() and forEach() method to iterate over the keys of mapped type record with the generic values. For each key, the associated generic value is retieved and printed....

Using Object.getOwnPropertyNames()

In this approach, we leverage the Object.getOwnPropertyNames() method to obtain an array of all property names of the mapped type record with generic values. We then iterate through these property names to access the corresponding generic values, enabling flexible handling of the record’s contents....

Contact Us