Conditional adding object properties in Javascript in one line

Elvis Ciotti
2 min readMar 27, 2023

--

One-liner code to add an element to an object without leaving the key without a value.

In JavaScript, you can conditionally add object properties using an if statement, a ternary operator or even a single instruction using the spread operator.

TL;DR;

{a:1, ...(yourConditionalBoolean && {b:2})  } // outputs {a: 1} or {a:1, b:2}

Using a “if” statement

Here’s an example using an if statement:

let person = { name: "John", age: 30 };
if (person.gender) {
person.gender = "Male";
}
console.log(person); // { name: "John", age: 30 }

person.gender = "Male";
if (person.gender) {
person.gender = "Female";
}
console.log(person); // { name: "John", age: 30, gender: "Female" }

In this example, we start with an object that has two properties, name and age. We check if the gender property exists on the person object using an if statement. If it does not exist, we do not add the property to the object. If it does exist, we set the value of the gender property to "Male". Then, we add the gender property to the person object and set its value to "Female". Finally, we log the person object to the console to verify that the properties have been added correctly.

Ternary operator

let person = { name: "John", age: 30 };
person.gender ? person.gender = "Male" : person.gender = "Female";
console.log(person); // { name: "John", age: 30, gender: "Female" }

In this example, we use a ternary operator to check if the gender property exists on the person object. If it does, we set the value of the gender property to "Male". If it does not, we set the value of the gender property to "Female". Finally, we log the person object to the console to verify that the property has been added correctly.

Single instruction using restructuring (3-dots operator)

const yourCondition = true;
{a:1, ...(yourCondition && {b:1}) } // {a:1, b:1} or {a:1} depending on the condition

If not clear, look at yourCondition && {b:1} : that simply means {b:1} if yourCondition is true. The && operator in JavaScript performs a boolean logical operation. It returns the value of its first operand if the first operand is falsy, and otherwise, it returns the value of its second operand.

The parentheses ( ) in the original code snippet are not strictly necessary, but they help to clarify the order of operations in the expression.

In JavaScript, the ... syntax is called the spread syntax. It allows an iterable (such as an array or object) to be expanded or "spread" into multiple elements or properties.

So what you have now is equivalent to {a:1, …{b:1}} that is basically {a:1, b:1}

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet