Open In App

How to Remove Object Properties with Lodash?

Last Updated : 23 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash is a powerful JavaScript utility library that makes manipulating arrays, objects, strings, and more easier. One of the common tasks when dealing with objects is removing properties, either based on specific criteria or simply for cleaning up unwanted data.

Below are the following ways to remove object properties with Lodash:

Using the _.omit() Method

The _.omit() method in Lodash creates a new object by omitting specified properties from an existing object. This is useful when we want to remove specific properties based on their keys.

Syntax:

_.omit(object, [paths])

Example: In the below code we use the _.omit() method to remove the email and address properties, returning a new object with only name and age.

JavaScript
const _ = require('lodash');

// Sample object
let user = {
    name: 'John Doe',
    age: 28,
    email: '[email protected]',
    address: '123 Main St'
};

// Remove 'email' and 'address' properties
let updatedUser = _.omit(user, ['email', 'address']);

console.log(updatedUser);

Output:

{name: "John Doe", age: 28}

Using the _.omitBy() Method

The _.omitBy() method removes object properties based on a predicate (function) that returns a boolean value. This is helpful when we want to omit properties based on specific conditions.

Syntax:

_.omitBy(object, predicate)

Example: In below code we use _.omitBy() method to remove the stock property because its value is 0. The predicate function checks if the value is 0, and if so, it omits that property.

JavaScript
const _ = require('lodash');

// Sample object
let product = {
    name: 'Laptop',
    price: 1200,
    stock: 0,
    discount: 0.15
};

// Remove properties where the value is 0
let updatedProduct = _.omitBy(product, value => value === 0);

console.log(updatedProduct);

Output:

name : "Laptop"
price : 1200
discount : 0.15

Using the _.pick() Method

The _.pick() method is the inverse of _.omit(). It creates a new object by picking only the specified properties, leaving out all others. This method is useful when we only want to keep a few specific properties from the original object.

Syntax:

_.pick(object, [paths])

Example: In this below code _.pick() method creates a new object containing only the name and occupation properties, omitting the age and salary properties.

JavaScript
const _ = require('lodash');

// Sample object
let person = {
    name: 'Jane Doe',
    age: 32,
    occupation: 'Engineer',
    salary: 80000
};

// Pick only 'name' and 'occupation'
let selectedPerson = _.pick(person, ['name', 'occupation']);

console.log(selectedPerson);

Output:

name : "Jane Doe"
occupation : "Engineer"

Next Article

Similar Reads