Filtering keys of an object involves selecting specific keys and creating a new object that contains only those keys. Using Lodash, this process allows you to include or exclude properties based on specific criteria, simplifying object manipulation.
Below are the approaches to filter keys of an object using Lodash:
Table of Content
Using _.pick() Method
This method allows us to create a new object by selecting specific keys from an existing object. It is similar to picking only what we need from the object.
Syntax:
_.pick(object, [keys])Example: In this example, the original user object has three keys, but the new object filteredUser only includes the name and email keys.
const _ = require('lodash');
const user = { name: 'Ram', age: 27, email: 'ram@example.com' };
const filteredUser = _.pick(user, ['name', 'email']);
console.log(filteredUser);
Output:
{ name: 'Ram', email: 'ram@example.com' }Using _.omit() Method
The _.omit() method from Lodash is used to generate a new object by excluding specified keys from the original object, providing a way to remove unwanted properties. This method is particularly useful when you want to filter out sensitive or irrelevant data before processing or displaying the object.
Syntax:
_.omit(object, [keys])Example: This code uses _.omit() to create a new object by excluding the age property from the user object.
const _ = require('lodash');
const user = { name: 'Shyam', age: 23, email: 'shyam@example.com' };
const filteredUser = _.omit(user, ['age']);
console.log(filteredUser);
Output:
{ name: 'Shyam', email: 'shyam@example.com' }