How to use Object.entries() and Array.filter() In Typescript
This method involves converting the dictionary into an array of key-value pairs using TypeScript’s Object.entries(). It then utilizes Array.filter() to selectively retain entries based on specified conditions, and finally reconstructs a dictionary from the filtered entries.
Syntax:
Object.entries(obj_name).filter(callback(element[, index[, array]])[, thisArg])
Example: The below code will explain the use of the Object.entries() and Array.filter() methods to filter dictionary in TypeScript.
const originalDictionary:
Record<string, any> =
{
name: 'w3wiki',
est: 2009,
CEO: 'Sandeep Jain'
};
const filteredEntries: [string, any][] =
Object.entries(originalDictionary).
filter(([key, value]) => {
return key !== 'est' &&
value !== "Sandeep Jain";
});
const filteredDictionary:
Record<string, any> =
Object.fromEntries(filteredEntries);
console.log(filteredDictionary);
Output:
{
name: "w3wiki"
}
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