Object Literal Conditional Properties
I’m constantly coming up against adding conditional properties to an Object, in an elegant fashion, but always have to end up doing:
var a = {};
if (someCondition) {
a.b = 5;
}
I’m sorry but this bothers me!
With the enhancements ES6 has brought to the good old Object, there must be a better way? Turns out the spread operator
is guy.
const a = {
...someCondition ? {b: 1} : {}
}
Now if … someCondition = true
we get a= {b: 1}
And if … someCondition = false
we only get a= {}
We can still improve on this syntactically mind you, by using the logical AND operator …
const a = {
...someCondition && {b: 1}
}
That’ll do it. By using short circuit evaluation, {b: 1}
will only get spread into a
if someCondition
evaluates to true
. If someCondition
is false
, someCondition
is returned, which being false
will not be spread into a
at all!