2

I'm looking for an idiomatic method of creating an object with an optional key, i.e. the shortest way of doing the following:

let obj = {a: 1}
if(condition)
    obj['b'] = 2
console.log(obj)

One way I've thought of is:

console.log({a: 1, ...(condition ? {b: 2} : {})})

But is there a better way?

simonzack
  • 19,729
  • 13
  • 73
  • 118

0 Answers0