Explain Codes LogoExplain Codes Logo

How to remove undefined and null values from an object using lodash?

javascript
lodash
omitby
isnil
Anton ShumikhinbyAnton Shumikhin·Aug 25, 2024
TLDR

Achieve the desired result in no time, by employing lodash's handy _.omitBy coupled with _.isNil:

const cleanObj = _.omitBy(obj, _.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:

// a function so happy, it could wag its tail const result = _.omitBy({ a: null, b: 1, c: undefined, d: false }, _.isNil); // here, result = { b: 1, d: false } — false gets to stay! 🥳

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:

function deepOmitBy(value, iteratee) { // a function as cunning as a fox if (_.isObject(value)) { return _.transform(value, (result, val, key) => { if (!iteratee(val)) { result[key] = deepOmitBy(val, iteratee); // going deeper 🦝 } }); } return value; } // just like a cleanup crew for a stubborn oil spill const deeplyCleanObject = deepOmitBy(nestedObj, _.isNil);

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.