📜  lodash omitBy - Javascript (1)

📅  最后修改于: 2023-12-03 15:02:47.414000             🧑  作者: Mango

Lodash OmitBy - Javascript

Lodash is a popular utility library for Javascript that provides a wide range of functions to make programming easier and efficient. One of the functions provided by Lodash is omitBy, which allows you to create a new object by omitting specific properties from an existing object based on a given condition.

Syntax

The syntax for omitBy function in Lodash is as follows:

_.omitBy(object, [predicate=_.identity])
  • object: The target object to omit the properties from.
  • predicate: The function invoked per property to determine if it should be omitted. The function is invoked with two arguments: (value, key).
Usage

Here is an example of how you can use omitBy function to omit all properties from an object whose value is undefined or null:

const _ = require('lodash');

const object = {
  name: 'John',
  age: 25,
  occupation: undefined,
  salary: null,
};

const result = _.omitBy(object, _.isNil);

console.log(result);

// Output: {name: 'John', age: 25}

In the above example, we have an object that contains four properties: name, age, occupation, and salary. We want to omit all the properties whose value is undefined or null. To achieve that, we have used _.isNil function as the predicate to check if a property value is undefined or null.

The output of the above example will be a new object that only contains name and age properties, since occupation and salary properties are undefined and null, respectively, and have been omitted.

Conclusion

The lodash omitBy function is a powerful tool for creating new objects by omitting specific properties based on a given condition. This function is just one of the many useful features provided by the popular Lodash utility library.