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.
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()
Contact Us