How to Conditionally Build An Object in Javascript With Es6

by Janeth Kent Date: 09-08-2019 javascript coding 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.

 
by Janeth Kent Date: 09-08-2019 javascript coding ES6 hits : 9348  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

Creating simple CSS spinner-loader

In today's article we will show you how to animate a basic loader that spins when some predefined action is defined, such as loading an image. That can be used…

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

A Java approach: While loop

Hello everyone and welcome back! After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

A Java approach: variables - use case

Hello all friends and welcome back! After the introduction made on the variables, we try to analyse some critical issues that may arise in quite common situations. Let's start by analysing…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration