Explain Codes LogoExplain Codes Logo

In JavaScript, how to conditionally add a member to an object?

javascript
conditional-properties
object-creation
javascript-syntax
Nikita BarsukovbyNikita Barsukov·Feb 23, 2025
TLDR

Leverage JavaScript's spread operator (...) to conditionally add properties to an object within the context of object literal syntax:

const hasSuperPowers = true; const hero = { name: 'Superman', ...(hasSuperPowers && { power: 'Flying' }) // "power" only added when hasSuperPowers is true };

Alternately, utilize a conventional if statement for straightforward conditional additions post object-creation:

let hero = { name: 'Batman' }; if (hasSuperPowers) hero.power = 'Genius Intellect'; // and insanity too

Safeguarding object integrity

To maintain the object's integrity, you can check for undefined or other faulty values. This is instrumental when dealing with data from external sources like APIs or user input:

let hero = { name: 'Robin' }; const power = fetchHeroPower('Robin'); // Relying on Nightwing's secret stash... // "power" is added only if power is not undefined if (power !== undefined) hero.power = power;

Scaling with multiple conditional properties

To conditionally add multiple properties within a single object, simply chain the spread structures:

const canFly = true, hasMoney = false; const hero = { name: 'Spiderman', ...(canFly && { power1: 'Flying' }), ...(hasMoney && { power2: 'Being Rich' }) // Sorry Spidey, you ain't rich! }; // hero now contains "name" and "power1" (flying), but not "power2"

Scale this pattern as required, making your code cleaner and more robust.

Conditional properties using Object.assign()

Object.assign() function can nimbly handle conditional properties:

const canFly = true; const hero = Object.assign( { name: 'Wolverine' }, canFly ? { power: 'Flying' } : null ); // Wolverine cannot fly, unless he's commuting by Air Canada

This method is beneficial for advanced scenarios where you pull values from multiple sources or objects with default properties.

jQuery's way to conditionals

For the jQuery proponents, $.extend() offers a neat solution:

const canFly = true; const hero = $.extend( { name: 'Flash' }, canFly && { power: 'Flying' } // Try catching a plane, Flash! );

This is akin to the spread syntax, reimagined for jQuery.

Pristine objects with short-circuiting

The logical AND (&&) operator keeps your objects clean, devoid of unrequired properties:

const canFly = false; const hero = { name: 'Aquaman', ...canFly && { power: 'Flying' } // Even a seahorse is faster than Aquaman in air };

Short-circuit evaluations will ensure properties are added only when the condition is strictly true.

Crafting dynamic objects using conditionals

Objects, much like superheroes, could be dynamic. Conditional properties allow you to shape them as per specific requirements:

const settings = { name: fetchHeroName() }; const hero = { ...settings, ...(isHeroHuman() && { weakness: 'Mortal Lifespan'}) // Applies to all, except Thor and Keanu Reeves };

Preventing property pollution with undefined checks

Complex data and cases can result in undefined values:

const heroAttributes = fetchHeroAttributesFromAPI(); const hero = { name: heroAttributes.name, ...(heroAttributes.age > 21 && { drinkingAge: true }) }; // "DrinkingAge" only gets added when age > 21 & heroAttributes.age is defined

This is a great strategy to keep your objects clean and maintain high fidelity in your data.