Explain Codes LogoExplain Codes Logo

Javascript - removing undefined fields from an object

javascript
object-cleanup
javascript-functions
performance-optimization
Anton ShumikhinbyAnton Shumikhin·Jan 10, 2025
TLDR

To remove undefined values from an object with built-in JavaScript methods, use Object.fromEntries(), Object.entries(), and Array.prototype.filter():

const omitUndefined = obj => Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined));

Example:

let obj1 = { x: 1, y: undefined, z: 2 }; obj1 = omitUndefined(obj1); console.log(obj1); // Output: { x: 1, z: 2 }

With this snippet, undefined values are excluded from the object.

Deep dive into object cleanup

When it comes to nested objects, a simple recursive function can remove undefined fields, making the process of undefined elimination in-depth.

const omitDeep = (obj) => { // Like the mythical Hydra, every object has a head(s). We aim for them all. Object.keys(obj).forEach(key => { if (obj[key] && typeof obj[key] === 'object') { omitDeep(obj[key]); // Recursive call for nested objects. } else if (obj[key] === undefined) { delete obj[key]; // "Off with its head!" - if it's undefined. } }); return obj; // Cleaned-up object. };

This function traverses every level of your object, ensuring zero undefined values remain.

JSON Trick: Just Say No

If the idea of using JSON.parse(JSON.stringify(obj)) crosses your mind as a quick fix, banish it; the method represents a double-edged sword, converting Date objects to strings and failing with circular references.

Dealing with other falsy values

While cleaning your object, you might come across falsy values like null or '' (empty string). Unless you want them gone too, ensure your condition explicitly checks for undefined only.

Falsy and non-falsy: The undefined dilemma

Although you might be tempted to use libraries like Lodash, consider focusing on pure JavaScript functions which can be reusable across different scenarios. Lodash's _.pickBy() with x => x filters all falsy values, but for undefined only, v => v !== undefined is the charm!

Check under the hood: Performance

Performance makes all the difference. Whilst the delete operator can be conveniently expressive, it's slower because it modifies the object's structure in-place. Always benchmark your options and choose wisely.

Alternative methods for object cleanup

Turn to reduce

Creating a new object excluding undefined values can be achieved using reduce() function along with Object.keys():

const excludeUndefined = obj => Object.keys(obj).reduce((acc, key) => { if (obj[key] !== undefined) { acc[key] = obj[key]; // Adds keys with defined values to new object. } return acc; // Returns new object. }, {});

Mutability vs. Immutability

Tampering with the original object – mutating it – might lead to unexpected side effects. Thus, stick to creating a new object.

Embrace modern JavaScript

Arrow functions, destructuring, and other ES6 features can increase the readability and conciseness of the code, like the fast answer provided earlier - no need to bring Gandalf to slay the Orcs (undefined values)!

The role of external libraries

Including external libraries brings extra dependencies. This could be avoided if the solution can be achieved natively. Choose wisely - Lodash vs. plain old JavaScript - the duel of the decade!