How to use Object.entries() and map() methods In Typescript
In this approach, we use the Object.entries() method which returns the array of key-value pairs from the object. Then by using the map method, we extract the keys from the filter’s key-value pairs by applying the filter condition. The resulting array is printed which are the keys of the type string.
Syntax:
const keyValuePairs: [string, any][] = Object.entries(object);
const mappedKeys: string[] = keyValuePairs
.filter(([_, value]) => /* condition */)
.map(([key]) => key);
Example: The below example filters the keys of string[] in TypeScript using Object.entries and map methods.
const data: { [key: string]: any } = {
title: 'w3wiki',
topics: ['Java', 'DSA', 'Web Dev'],
author: 'GFG User 3',
};
const res: string[] = Object.entries(data)
.filter(([_, value]) => typeof value === 'string')
.map(([key]) => key);
console.log(res);
Output:
["title", "author"]
How to Filter Keys of Type string[] in TypeScript ?
In TypeScript, the filtering of keys of type string[] can be done by iterating over the data object, and applying the condition to the string if the key is a string. If the condition is satisfied, then an array of output results is created which consists of filtered keys of type string[]. The below methods can be used to filter the keys of type string[].
Table of Content
- Using the for/in Loop
- Using the Object.keys() and filter() methods
- Using Object.entries() and map() methods
- Using Object.getOwnPropertyNames()