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.
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()andArray.prototype.filter()to remove the keys for whichfnreturns 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.