![]() |
In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for…of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows: Using for…of LoopIn this approach, we use a for…of loop to iterate over an array of objects (arr), where each data represents an object of the defined interface obj. It prints the name and role properties of each object to the console. Syntax:for (const element of iterable) { Example: The below example uses for…of Loop to iterate an array of objects in TypeScript.
Output: Name: GFG User 1, Role: Developer Using forEach methodIn this approach, we are using the forEach method to iterate through an array of objects (arr), where each data object of type obj is accessed to print the name and role properties, Syntax:array.forEach((element: ElementType, index: number, array: ElementType[]) => { Example: The below example uses forEach method to iterate an array of objects in TypeScript.
Output: Name: GFG User 1, Role: Developer Using map methodIn this approach, we are using the map method on an array of objects (arr) in TypeScript to iterate over each object, prints its properties (name and role), and return the original data. Syntax:const newArray = array.map((element: ElementType, index: number, array: ElementType[]) => { Example: The below example uses map method to iterate an array of objects in TypeScript.
Output: Name: GFG User 1, Role: Developer Using reduce MethodAnother approach to iterate over an array of objects in TypeScript is by using the reduce method. This method can be particularly useful when you need to accumulate or aggregate data from the array. The reduce method applies a function against an accumulator and each element in the array to reduce it to a single value. Example: The below example uses the reduce method to iterate over an array of objects in TypeScript and accumulates the names and roles into a new array of strings.
Output: Name: GFG User 1, Role: Developer |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |