Pick 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 pick function in JavaScript to extract specific key-value pairs from an object. We will learn how to pass an object and an array of keys to the pick function and how it uses Array.prototype.reduce() to filter and return only the specified key-value pairs from the object. This lab will help you understand how to work with objects in JavaScript and how to extract only the necessary information from them.


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-28544{{"`Pick Object Keys`"}} javascript/data_types -.-> lab-28544{{"`Pick Object Keys`"}} javascript/arith_ops -.-> lab-28544{{"`Pick Object Keys`"}} javascript/comp_ops -.-> lab-28544{{"`Pick Object Keys`"}} javascript/array_methods -.-> lab-28544{{"`Pick Object Keys`"}} javascript/higher_funcs -.-> lab-28544{{"`Pick Object Keys`"}} javascript/destr_assign -.-> lab-28544{{"`Pick Object Keys`"}} end

Instructions for Picking Object Keys

To pick specific key-value pairs from an object, use the function pick(obj, arr).

  • Pass in the object as the first argument and an array of keys to pick as the second argument.
  • The function returns a new object with only the key-value pairs that correspond to the given keys.

Here's an example of how to use pick():

const pick = (obj, arr) =>
  arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});

pick({ a: 1, b: "2", c: 3 }, ["a", "c"]); // { 'a': 1, 'c': 3 }

To get started with coding practice, open the Terminal/SSH and type node.

Summary

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

Other JavaScript Tutorials you may like