Pick Matching Object Keys

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to use the pickBy() function to create a new object composed of only the key-value pairs for which a given function returns truthy. This function can be useful in scenarios where you need to filter out certain properties from an object based on certain criteria. We will learn how to use Object.keys(), Array.prototype.filter(), and Array.prototype.reduce() to accomplish this task.


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`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28543{{"`Pick Matching Object Keys`"}} javascript/data_types -.-> lab-28543{{"`Pick Matching Object Keys`"}} javascript/arith_ops -.-> lab-28543{{"`Pick Matching Object Keys`"}} javascript/comp_ops -.-> lab-28543{{"`Pick Matching Object Keys`"}} javascript/array_methods -.-> lab-28543{{"`Pick Matching Object Keys`"}} javascript/higher_funcs -.-> lab-28543{{"`Pick Matching Object Keys`"}} javascript/destr_assign -.-> lab-28543{{"`Pick Matching Object Keys`"}} end

Function to pick object keys that match a given condition

To pick object keys that match a given condition, use the pickBy() function. This function creates a new object composed of the properties for which the given function returns a truthy value.

  • Use Object.keys() and Array.prototype.filter() to remove the keys for which fn returns a falsy value.
  • Use Array.prototype.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.
  • The callback function is invoked with two arguments: (value, key).

Here's the code for the pickBy() function:

const pickBy = (obj, fn) =>
  Object.keys(obj)
    .filter((k) => fn(obj[k], k))
    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});

You can use this function to pick keys that match a condition. For example:

pickBy({ a: 1, b: "2", c: 3 }, (x) => typeof x === "number");
// { 'a': 1, 'c': 3 }

Summary

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

Other JavaScript Tutorials you may like