Find First Matching Key

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the implementation of a JavaScript function called findKey. This function is designed to help us find the first key in an object that satisfies a provided testing function. By using Object.keys() and Array.prototype.find(), we can efficiently search through the properties of an object and return the desired key.


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/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28302{{"`Find First Matching Key`"}} javascript/data_types -.-> lab-28302{{"`Find First Matching Key`"}} javascript/arith_ops -.-> lab-28302{{"`Find First Matching Key`"}} javascript/comp_ops -.-> lab-28302{{"`Find First Matching Key`"}} javascript/array_methods -.-> lab-28302{{"`Find First Matching Key`"}} javascript/destr_assign -.-> lab-28302{{"`Find First Matching Key`"}} end

Function to Find First Key Matching a Test

To find the first key in an object that matches a given test function, use the findKey() function. First, obtain all the object properties using Object.keys(). Then, apply the test function to each key-value pair using Array.prototype.find(). The test function should take in three arguments: the value, the key, and the object. The function returns the first key that satisfies the test function or undefined if none is found.

Here's an example implementation of findKey():

const findKey = (obj, fn) =>
  Object.keys(obj).find((key) => fn(obj[key], key, obj));

To use findKey(), pass in the object and the test function as arguments:

findKey(
  {
    barney: { age: 36, active: true },
    fred: { age: 40, active: false },
    pebbles: { age: 1, active: true }
  },
  (x) => x["active"]
); // 'barney'

In this example, findKey() returns the first key in the object where the value of the active property is true, which is 'barney'.

Summary

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

Other JavaScript Tutorials you may like