Matt Chaffe

ES6 Shorthands

Optional Object Properties

To add additional props to an object in a terse way, we can simply do the following:

const value = 'Matt'
const obj = {
  gender: 'male',
  ...value && { name: value }
}

If value is truthy, it will add name: 'Matt' to the object.

Can also be written like:

const value = 'Matt'
const obj = {
  gender: 'male',
  ...(value ? { name: value } : {})
}