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
  • 17,855
  • 12
  • 65
  • 107

0 Answers0