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 }
How the Predicate Works
The predicate gets two arguments:
(value, key) => {
// value → the property value
// key → the property key as a string
}
Example:
omitBy(obj, (value, key) => key === 'age');
// removes any property where the key is "age"
Common Uses
- Remove null or undefined fields
omitBy(obj, value => value == null);
- Remove all falsy values (false, 0, '', null, undefined, NaN)
omitBy(obj, value => !value);
- Remove keys by name pattern
omitBy(obj, (value, key) => key.startsWith('_'));
// removes any key starting with underscore
Difference from omit
- omit → remove by key names you already know:
**_.omit(obj, ['age', 'city']);*
- omitBy → remove by a condition (calculated dynamically for each key).
Top comments (0)