Find Matching Keys

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to find all the keys in a JavaScript object that match a given value. By using Object.keys() and Array.prototype.filter(), we can efficiently search through an object and return an array of keys that correspond to the provided value. This will be a valuable skill for any JavaScript developer working with complex data structures.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28308{{"`Find Matching Keys`"}} javascript/data_types -.-> lab-28308{{"`Find Matching Keys`"}} javascript/arith_ops -.-> lab-28308{{"`Find Matching Keys`"}} javascript/comp_ops -.-> lab-28308{{"`Find Matching Keys`"}} javascript/array_methods -.-> lab-28308{{"`Find Matching Keys`"}} javascript/higher_funcs -.-> lab-28308{{"`Find Matching Keys`"}} end

Find Matching Keys

To find all the keys in an object that match a given value, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Object.keys() to get all the properties of the object.
  3. Use Array.prototype.filter() to test each key-value pair and return all keys that are equal to the given value.

Here's an example function that implements this logic:

const findKeys = (obj, val) =>
  Object.keys(obj).filter((key) => obj[key] === val);

You can use this function like this:

const ages = {
  Leo: 20,
  Zoey: 21,
  Jane: 20
};
findKeys(ages, 20); // [ 'Leo', 'Jane' ]

Summary

Congratulations! You have completed the Find Matching Keys lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like