How to use for…in Loop In Javascript
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.
Syntax:
for (variable in object) {
// code
}
Example: The below example uses for…in the loop to iterate through mapped type record with generic value in TypeScript.
type obj1 = {
topic: string;
difficulty: number;
};
const gfgData: Record<string, obj1> = {
algorithm: {
topic: "Algorithms",
difficulty: 3
},
dataStructure: {
topic: "Data Structures",
difficulty: 2
},
language: {
topic: "Programming Languages",
difficulty: 1
},
};
for (const key in gfgData) {
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