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.
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.