How to use Object.keys() and Array.filter() In Typescript
This approach focuses on leveraging TypeScript’s Object.keys() method to extract the keys of a dictionary. Subsequently, it employs the Array.filter() method to selectively retain entries based on specified conditions, allowing for an efficient and concise filtering mechanism.
Syntax:
Object.keys(obj_name).filter(callback(element[, index[, array]])[, thisArg])
Example: The below code will explain the use of the Object.keys() and Array.filter() methods to filter the dictionary in TypeScript.
const originalDictionary:
Record<string, any> =
{
name: 'John',
age: 25,
city: 'New York'
};
const filteredKeys =
Object.keys(originalDictionary).
filter(key => {
return key !== 'age';
});
const filteredDictionary:
Record<string, any> = {};
filteredKeys.forEach(key => {
filteredDictionary[key] =
originalDictionary[key];
});
console.log(filteredDictionary);
Output:
{
name: "John",
city: "New York"
}
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