Object Literals and Spread Operator

In this tutorial we will learn how to take advantage of spread operator in order to initialise a new object with optional properties.
Let’s start from a very basic example. We can create a new object with following key-value notation:
const object = {
a: 'foo',
b: 123,
c: { obj: 'bar' }
};
However, we can convert values into variables:
const value1 = 'foo';
const value2 = 123;
const value3 = { obj: 'bar' };const object = {
a: value1,
b: value2,
c: value3
}
Overall, the result is the same.
If we take advantage of ECMAScript2015 notation we can simplify it even further:
const a = 'foo';
const b = 123;
const c = { obj: 'bar' };const object = {
a,
b,
c
}
Now, let’s create a scenario when one of the properties is optional. We want to return the same object if all values are set or remove optional property:
const a = 'foo';
const b = undefined; // Optional
const c = { obj: 'bar' };const object = {
a,
b,
c
}
This will however, yield:
Object {a: "foo", b: undefined, c: {obj: "bar"}}
While what we expect to get is:
Object {a: "foo", c: {obj: "bar"}}
There are a few techniques available that will give the correct and expected result. However, one of the coolest is to use spread operator:
const a = 'foo';
const b = undefined; // Optional
const c = { obj: 'bar' };const object = {
a,
...(b && {b}),
c
}
Which returns:
Object {a: "foo", c: {obj: "bar"}}
With spread operator we achieved exactly what we wanted! However, how did that work?
Basically, logical AND operator &&
returns object {b}
to spread operator if condition b
is true
and this will be true
for all objects b
that havetruthy
value. If the value is falsy
then no object will be returned to spread operator.
If you like this tutorial then please like, share and follow me. If you have questions or maybe you have a different technique please don’t be afraid to comment below.