How to remove undefined and null values from an object using lodash?
Achieve the desired result in no time, by employing lodash's handy _.omitBy
coupled with _.isNil
:
Now, cleanObj
contains your object, devoid of any null
or undefined
bogies.
Aiming for precision with omitBy
and isNil
The function _.omitBy
takes an object and a predicate, producing a new object that excludes the properties for which the predicate returns true. When clubbed with _.isNil
, it checks for null
or undefined
values, ensuring precise removal.
In our case, the predicate function is _.isNil
, which checks if the passed value is null
or undefined
. This combination targets null
and undefined
values, while preserving false
, 0
, ""
, and NaN
, considered falsey JavaScript values.
Efficient pruning with lazy evaluation
For large objects or performance-critical scenarios, lazy evaluation — deferring computation until necessary — can provide a significant performance boost. Lodash supports this with chain sequences, which have some methods that implicitly end the chain sequence and unwrap the unwrapped value.
In plain language: if lodash were a dog, it wouldn't fetch all the sticks at once; it'd fetch them as needed. Good boy, lodash! 🐶
Falsey values: misunderstood, yet valuable
Using _.isNil
only targets null
and undefined
values, leaving falsey values, such as false
, untouched:
Edge cases with nested objects
As is often the case in JavaScript, things can get a bit... nested. For objects with nested structure, you need to deep dive. Use a custom recursive function alongside lodash:
Excluding nulls and undefines, the lodash way
Lodash holds the ace for data sanitation. Using lodash methods like _.omitBy
or even _.pickBy
with the predicate _.isNil
ensures null and undefined values are omitted, while falsey values are retained.
Was this article helpful?