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?
Object.assign. Like,let obj = {a: 1} obj = Object.assign(obj, condition ? {b:1} : {})conditionand the key'b'? Is there a particular nature to the object that could help inform the decision. To me the first version is perfectly readable.