How to use the for…in loop In Typescript
This traditional approach uses a for…in loop to iterate over the keys of the original dictionary. It selectively populates a new dictionary based on specified conditions, offering a straightforward and intuitive method for filtering.
Syntax:
for (let variable in object) {
// code to be executed
}
Note: It’s important to note that for…in should be used with objects, and not with arrays. If you want to iterate over the elements of an array, it’s recommended to use a for…of loop instead.
Example: The below code implements the for/in loop to filter dictionary in TypeScript.
const originalDictionary:
Record<string, any> =
{
name: 'w3wiki',
est: 2009,
city: 'Noida'
};
const filteredDictionary:
Record<string, any> = {};
for (const key in originalDictionary) {
if (key !== 'city') {
filteredDictionary[key] =
originalDictionary[key];
}
}
console.log(filteredDictionary);
Output:
{
name: "w3wiki",
age: 2009
}
Filter a Dictionary by Key or Value in TypeScript
Filtering a dictionary by key or value is a common task in TypeScript when working with data structures. TypeScript provides various approaches to achieve this efficiently.
Table of Content
- Using Object.keys() and Array.filter()
- Using Object.entries() and Array.filter()
- Using the for…in loop
- Using reduce Method
Contact Us