How to filter an object by key - JavaScript

Mo Ibra

Mo Ibra

Jan 5, 2023

In this article we will learn how to filter an object by key in JavaScript.

It is very common to filter an object by key in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to filter an object by key.

Imagine you have an object like this:

// Object
const myObject = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30
};

And we want to filter this object by key.

For example, we only want keys that contain the word name.

How to solve this problem?

This problem is not difficult to solve, all we will do is convert the object into an array and then filter the array, and then return it back to an object.

The solution will be as follows:

  • Convert the object into an array using Object.entries.
  • Filter the array using filter method.
  • Return it back to an object using fromEntries().

Filter an object using filter

As we said before, we will use filter method to solve our problem.

But first we need to convert the object into an array.

// Object
const obj = { firstName: 'John', lastName: 'Doe', age: 30 };

// Convert to an array
const toArr = Object.entries(obj);

// Result:
console.log(toArr);

Output

[ [ 'firstName', 'John' ], [ 'lastName', 'Doe' ], [ 'age', 30 ] ]

Now we have to filter the array using a filter method.

// Object
const obj = { firstName: 'John', lastName: 'Doe', age: 30 };

// Convert to an array
const toArr = Object.entries(obj);

// Filter array
const filter = toArr.filter(([key]) => key.includes('Name'));

console.log(filter);

Output

[ [ 'firstName', 'John' ], [ 'lastName', 'Doe' ] ]

Now that the array has been filtered, we will return the array to an object again using fromEntries() method.

// Convert to an object again
const toObj = Object.fromEntries(filter);

// Result:
console.log(toObj);

Output

{ firstName: 'John', lastName: 'Doe' }

The Object.fromEntries() static method transforms a list of key-value pairs into an object. MDN


Full Code:

// Object
const obj = { firstName: 'John', lastName: 'Doe', age: 30 };

// Convert to an array
const toArr = Object.entries(obj);

// Filter object
const filter = toArr.filter(([key]) => key.includes('Name'));

console.log(filter);

// Convert to an object again
const toObj = Object.fromEntries(filter);

// Result:
console.log(toObj);

Output

{ firstName: 'John', lastName: 'Doe' }

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: