Conditional object properties

Bergi a.d.bergi at web.de
Wed Nov 2 20:53:17 UTC 2016


Luke Mitchell schrieb:
> Hi all,
>
> I often come across a situation where I wish to extend an object
> (usually an argument for an API request) if a particular condition is
> satisfied, such as the presence of a function parameter. Currently the
> only way to do this is by assigning the object to a variable, checking
> the condition using an `if` statement and then extending the object. I
> am proposing the inclusion of an operator that allows a property to be
> included, subject to a particular condition, inside the object
> definition.

You can already do
```js
let obj = Object.assign({
     …
}, cond ? { prop: value } : null);
```
Or depending on your condition, also just `cond && { prop: value }`.

The object spread proposal will achieve the same, without the need for 
any extra operator.

- Bergi


More information about the es-discuss mailing list