Introduction
Sometimes you’re creating a javascript object to send in a network requset for example and you want to add a property if a specific condition is met. In the past we had to use conditions to do that, but ES6 gave us a shortcut to do that using the spread operator. That’s what we’ll see in the next sections.
Problem
You want to send the data
object in an HTTP request, and if the gender proerty is provided you wanna attach it to the data object. Otherwise, you want to omit it.
1const data = {2 first_name: 'Joe',3 last_name: 'Doe'4}
Old Solution
In the past, you would need to use an if condition to check if the property has a value or not to add it to the data
object as follows
1const data = {2 first_name: 'Joe',3 last_name: 'Doe'4}56const gender = 'male'78if(gender) {9 data.gender = gender10}1112console.log(data)13// {14// first_name: 'Joe',15// last_name: 'Doe'16// gender: 'male'17// }
Obviously, this required multiple lines of code to add that simple property to the JS object. Alternatively, you can use the ES6 shortcut syntax for this as you’ll see in the next section.
ES6 Solution
In ES6, you can use the spread operator to add the key/property to the JS object if it exists, and omit it if it doesn’t as you can see this snippet
1const gender = 'male'23const data = {4 first_name: 'Joe',5 last_name: 'Doe',6 ...(gender && {gender})7}89console.log(data)10// {11// first_name: 'Joe',12// last_name: 'Doe'13// gender: 'male'14// }
This is the abstract format of the optional key addition using the ES6 syntax
1const yourObject = {2 ...(condition && {keyName: value})3}
Conclusion
I hope this article helped you with your work. If you’re interested in getting up to date with the latest JS news and trends, don’t forget to subscribe to my newsletter. Promise, I won’t spam you!