When using Lodash to filter object keys, we can use the _.pick or _.omit methods to retain or exclude certain properties as needed. Both methods can filter an object based on a specified array of keys.
Using the _.pick Method
The _.pick method creates an object composed of selected keys. For example, if we have the following object and we only want to retain specific keys (such as 'name' and 'age'), we can use _.pick:
javascriptconst _ = require('lodash'); const person = { name: 'John Doe', age: 30, job: 'Developer' }; const pickedPerson = _.pick(person, ['name', 'age']); console.log(pickedPerson); // Output: { name: 'John Doe', age: 30 }
In this example, pickedPerson contains only the name and age properties, with the job property filtered out.
Using the _.omit Method
Conversely, if we want to exclude certain keys, we can use the _.omit method. For example, using the same person object, if we want to exclude the job property:
javascriptconst omittedPerson = _.omit(person, ['job']); console.log(omittedPerson); // Output: { name: 'John Doe', age: 30 }
In this example, omittedPerson does not include the job property and only retains the name and age properties.
Summary
Choose between _.pick and _.omit based on your specific needs: use _.pick if you know exactly which keys you need, and use _.omit if you know which keys you don't need. Both methods are highly effective and practical Lodash tools for handling object properties.