Optional object properties

Published 
JavaScript

Sometimes there's a need to conditionally show properties in an object, there's one clean way to do that:

let flag1 = true
let flag2 = false

const obj = { 
  requiredKey1: 1, 
  requiredKey2: 2,
  ...(flag1 && { optionalKey1: 5 }),
  ...(flag2 && { optionalKey2: 6, optionalKey3: 7 }),
  ...(flag1 && { optionalKey4: 8, optionalKey5: 9 })
}

flag1 values will be present in this object, while flag2 not.