How Lodash omitBy Filters Object Properties

The _.omitBy method in the Lodash JavaScript library creates a shallow clone of an object, excluding all properties for which a given predicate function returns a truthy value. Instead of manually specifying fixed keys to remove, developers can evaluate each key-value pair dynamically against custom logic, making it particularly useful for cleaning up payloads, removing nullish data, or stripping out specific data types. This article breaks down the mechanics of _.omitBy, its syntax, and how its predicate function evaluates properties to filter them out.

Understanding the Syntax and Parameters

The basic syntax of _.omitBy is:

_.omitBy(object, [predicate=_.identity])

The method returns a brand-new object containing only the properties where the predicate returned a falsy value. The original object remains unmodified.

How the Predicate Function Evaluates Properties

Under the hood, _.omitBy iterates over the enumerable string-keyed properties of the source object. During each iteration, it passes the current property’s value and key to the predicate function.

The fundamental rule of _.omitBy is:

This behavior is the exact inverse of _.pickBy, which keeps properties when the predicate evaluates to truthy.

Practical Examples

1. Removing Null or Undefined Values

A common use case is stripping out unset properties from an API request payload using Lodash’s built-in _.isNil helper.

const _ = require('lodash');

const userData = {
  name: 'Alex',
  age: 29,
  email: null,
  phoneNumber: undefined,
  active: true
};

const cleanedData = _.omitBy(userData, _.isNil);

console.log(cleanedData);
// Output: { name: 'Alex', age: 29, active: true }

In this scenario, _.isNil(value) returns true for email and phoneNumber, causing _.omitBy to exclude them from the output object.

2. Filtering by Value Type

You can define inline predicate functions to discard specific data types, such as numbers or booleans:

const rawInput = {
  id: 101,
  title: 'Report',
  views: 0,
  isDraft: false,
  description: 'Monthly summary'
};

// Omit any property whose value is a number
const nonNumeric = _.omitBy(rawInput, (value) => typeof value === 'number');

console.log(nonNumeric);
// Output: { title: 'Report', isDraft: false, description: 'Monthly summary' }

3. Filtering Using Property Keys

The predicate also receives the property key as its second parameter, allowing exclusions based on key naming conventions:

const internalRecord = {
  id: 'abc-123',
  title: 'Project Alpha',
  _internalId: 98765,
  _checksum: 'd41d8cd98f00b204e9800998ecf8427e'
};

// Omit properties starting with an underscore
const publicRecord = _.omitBy(internalRecord, (value, key) => key.startsWith('_'));

console.log(publicRecord);
// Output: { id: 'abc-123', title: 'Project Alpha' }

Key Considerations