How to use the Object.keys() and filter() methods In Typescript
In this approach, we use Object.keys() method to get the array of keys from the object. Then the filter method is applied to this array by keeping only the keys that are of type string. The result array consists of only the filtered keys which are of type string[].
Syntax:
const filteredKeys: string[] = Object.keys(object)
.filter(key => /* condition */);
Example: The below example filters the keys of string[] in TypeScript using Object.keys and filter methods.
const data: { [key: string]: any } = {
title: 'w3wiki',
topics: ['Java', 'DSA', 'Web Dev'],
author: 'GFG User 2',
};
const res: string[] =
Object.keys(data).
filter(key => typeof data[key] === 'string');
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()
Contact Us