How to Filter an Object by Key in JavaScript

Introduction

JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object. filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.

If you'd like to read more about the filter() method - read our Guide to JavaScript's filter() Method!

In this article, we will explore how to filter an Object making use of its key in JavaScript.

An object is, essentially, a map of properties and their values. This key-value pair set is what an object is. We can naturally extract the keys and values individually:

Keys are extracted using Object.keys(), while values are extracted using Object.values(). To retrieve both keys and values, you may alternatively use Object.entries(). We are solely concerned with the keys in this article, for filtering keys against certain criteria.

Using Object.keys() to filter an Object

The Object.keys() method is used to generate an array whose elements are strings containing the names (keys) of an object's properties. The object is passed as an argument to Object.keys():

Object.keys(objectName);

For example, suppose we have an object of user scores in various subjects:

const userScores = {
    chemistry: 60,
    mathematics: 70,
    physics: 80,
    english: 98
};

We can loop through the object and fetch the keys, which for this example would be the subjects:

const names = Object.keys(userScores);
console.log(names); // ["chemistry","mathematics","physics","english"]

After you've generated the keys, you may use filter() to loop over the existing values and return just those that meet the specified criteria. Finally, you can use reduce() to collect the filtered keys and their values into a new object, for instance.

Note: filter() is great at chaining with other functional methods!

Assume we have an Object, and we want to return only key-value pairs with the word "name" in the keys:

const user = {
    firstName: "John",
    lastName: "Doe",
    userName: "johndoe12",
    email: "[email protected]",
    age: 37,
    hobby: "Singing"
};

We could filter by making use of the Objects key:

const names = Object.keys(user)
    .filter((key) => key.includes("Name"))
    .reduce((obj, key) => {
        return Object.assign(obj, {
          [key]: user[key]
        });
  }, {});

console.log(names);

We made use of Object.keys(user) to generate all the keys as an array, resulting in an array:

["firstName","lastName","userName","email","age","hobby"]

We then used the array function includes() as the criteria, within the filter() method, to go over each element in the array to determine whether any key included the word "Name":

["firstName","lastName","userName"]

Then, we made use of reduce() to reduce the array down into an object.

Note: The reduce() function accepts two arguments: an object as the first parameter (identity) and the current iteration value as the second.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

We are using Object.assign() to combine source objects into a target object in the new object being generated. The Object.assign() function takes the Object that is being built and adds the current key-value pair that we are passing into it.

And at the end of this - we have a new object, filtered by the keys:

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

Filter Array of Objects by Key

Oftentimes, the objects we're processing are sequenced in an array. Filtering each is as easy as filtering one - we just iterate through the array and apply the same steps:

const users = {
    John: { username: 'johncam112', age:19 },
    Daniel: { key: 'Dandandel1', age:21 },
    Ruth: { key: 'rutie01', age:24 },
    Joe: { key: 'Joemathuel', age:28 }
};

const selectedUsers = ['Ruth', 'Daniel'];

const filteredUsers = Object.keys(users)
    .filter(key => selectedUsers.includes(key))
    .reduce((obj, key) => {
        obj[key] = users[key];
        return obj;
  }, {});

console.log(filteredUsers);

In the above example, we filtered the Users object to only return objects of the selectedUsers, filtering them by the key:

{
    Daniel: {
        key:"Dandandel1",
        age:21
},
    Ruth: {
        key:"rutie01",
        age:24
    }
}

Conclusion

In this short article - we've taken a look at filtering objects by value, using the Object.keys() method, filtered via the filter() method.

Last Updated: March 17th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms