![]() |
VOOZH | about |
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:
_.omit() MethodThe _.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.
_.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.
Output:
{name: "John Doe", age: 28}_.omitBy() MethodThe _.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.
_.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.
Output:
name : "Laptop"
price : 1200
discount : 0.15
_.pick() MethodThe_.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.
_.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.
Output:
name : "Jane Doe"
occupation : "Engineer"