Open In App

How to Filter Key of an Object using Lodash?

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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.

JavaScript
const _ = require('lodash');

const user = { name: 'Ram', age: 27, email: '[email protected]' };
const filteredUser = _.pick(user, ['name', 'email']);
console.log(filteredUser);

Output:

{ name: 'Ram', email: '[email protected]' }

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.

JavaScript
const _ = require('lodash');

const user = { name: 'Shyam', age: 23, email: '[email protected]' };
const filteredUser = _.omit(user, ['age']);
console.log(filteredUser);

Output:

{ name: 'Shyam', email: '[email protected]' }

Next Article

Similar Reads