How to conditionally build an object in JavaScript with ES6

How to conditionally build an object in JavaScript with ES6

The arrival of ES6 brought us, among many other news, the spread syntax, which, as you will already know, allows us to save a few lines of code and improve legibility.

Specifically, this syntax allows us to destructure the parameters that we pass to a function so that our code goes from:

function foo(data) {
const id = data.id
const title = data.name
// more...
}

to

function foo({id, title}) {
//more
}

But also thanks to the operator spread ... , we can expand (unwrap) objects in order to perform operations such as:

const obj1 = {a: 1, b: 2};
const obj2 = {...obj1, c: 3};
// obj2 = {a: 1, b: 2, c: 3};

However, another implementations of this syntax is to create objects with certain properties dependent on a condition, which is what I wanted to talk about in this article.

For example, if we have the following code:

const obj1 = {a: 1, b: 2};
if (condition) {
ob1.c = 3;
}
if (otherCondition) {
obj.d = 4;
}const obj1 = {a: 1, b: 2};
if (condition) {
ob1.c = 3;
}
if (otherCondition) {
obj.d = 4;
}

By using the spread syntax we can transform it into the following, much more readable:

const obj1 = {
a: 1, 
b: 2,
...(condition ? {c:3} : {}),
...(otherCondition ? {c:4} : {})
};

This is possible because the operator only acts if the condition is true. Remember that if you are going to use this way of creating objects, 0 evaluates to false so you should perform a strict check.

As you can see, using this operator allows us to improve our code a lot and get rid of those annoying ifs we had to add if we wanted to achieve something similar.