DEV Community

Ola Abaza
Ola Abaza

Posted on

1 RN Thing a Day – Day 4: Usage of omitBy

In Lodash, _.omitBy creates a new object by removing properties where the predicate function returns true.

_.omitBy is only for objects (key–value pairs), not for arrays of values.
If you have an object → use omitBy (removes properties based on a condition) or pickBy (Keeps properties based on a condition).
If you have an array → use filter (removes items based on a condition) or map (transforms each item).

What omitBy Does
_.omitBy(object, predicate)

  • Loops over each property of the given object.
  • Runs your predicate function for every (value, key).
  • If predicate returns true, that property is removed from the new object.
  • Returns a new object (does not modify the original).

Think of it as the opposite of _.pickBy — instead of keeping matching properties, you remove them.

Basic Example

import omitBy from 'lodash/omitBy';

const obj = {
  name: 'Ola',
  age: 0,
  active: false,
  city: null
};

const result = omitBy(obj, (value) => value == null);
// removes `null` and `undefined`

console.log(result);
// { name: 'Ola', age: 0, active: false }
Enter fullscreen mode Exit fullscreen mode

How the Predicate Works
The predicate gets two arguments:

(value, key) => {
  // value → the property value
  // key   → the property key as a string
}
Enter fullscreen mode Exit fullscreen mode

Example:

omitBy(obj, (value, key) => key === 'age');
// removes any property where the key is "age"
Enter fullscreen mode Exit fullscreen mode

Common Uses

  • Remove null or undefined fields
omitBy(obj, value => value == null);

Enter fullscreen mode Exit fullscreen mode
  • Remove all falsy values (false, 0, '', null, undefined, NaN)
omitBy(obj, value => !value);

Enter fullscreen mode Exit fullscreen mode
  • Remove keys by name pattern
omitBy(obj, (value, key) => key.startsWith('_'));
// removes any key starting with underscore

Enter fullscreen mode Exit fullscreen mode

Difference from omit

  • omit → remove by key names you already know:
**_.omit(obj, ['age', 'city']);*

Enter fullscreen mode Exit fullscreen mode
  • omitBy → remove by a condition (calculated dynamically for each key).

Top comments (0)