ES6 Conditional Object Assignment

Sometimes you need to add a set of key / value pairs to a Javascript object when a condition is met, and do nothing to the object otherwise.

An easy solution is the obvious:

if (condition) {  
    myObject[key] = value;
    myObject.otherKey = otherValue;
}

But often it's nicer to be more concise, especially when pure expressions are neater to use than statements + expressions (in a map closure, in the options of a React component prop, etc).

But you can't use the ternary operator:

myObject = {  
    key: condition ? value : null
}

because it necessitates a value being set in the negative case of the condition.

This StackOverflow answer describes another approach, which though more cryptic, can be a better option in a lot of simple cases. Note it does require the ES6 spread operator.

myObject = {  
    ...myCondition && {key: value, otherKey: otherValue}
}

The trick is taking advantage of the fact that the && boolean operator actually returns the right hand side if the entire expression evaluates to true.

The right hand side is a plain object, which then has the spread operator acted on it, thus inserting the values into the original object.