Open In App

Filter a Dictionary by Key or Value in TypeScript

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Using Object.keys() and Array.filter()

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.

Javascript
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"
}

Using Object.entries() and Array.filter()

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.

Javascript
const originalDictionary:
    Record<string, any> =
{
    name: 'GeeksforGeeks',
    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: "GeeksforGeeks"
}

Using the for…in loop

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.

Javascript
const originalDictionary:
    Record<string, any> =
{
    name: 'GeeksforGeeks',
    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: "GeeksforGeeks",
    age: 2009
} 

Using reduce Method

This approach employs a functional programming style with TypeScript’s reduce method. It iterates over the keys of the original dictionary, selectively adding key-value pairs to the filtered dictionary based on specified conditions.

Syntax:

const filteredDictionary = Object.keys(originalDictionary).reduce((acc, key) => {
    if (typeof originalDictionary[key] === 'string') {
        acc[key] = originalDictionary[key];
    }
    return acc;
}, {} as Record<string, any>);

Example:

JavaScript
const originalDictionary: Record<string, any> = {
    name: 'GeeksforGeeks',
    est: 2009,
    city: 'Noida'
};

const filteredDictionary = Object.keys(originalDictionary).reduce((acc, key) => {
    if (typeof originalDictionary[key] === 'string') {
        acc[key] = originalDictionary[key];
    }
    return acc;
}, {} as Record<string, any>);

console.log(filteredDictionary);

Output:

{
    name: "GeeksforGeeks",
    city: "Noida"
}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads