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?

6
  • You could also use, Object.assign. Like, let obj = {a: 1} obj = Object.assign(obj, condition ? {b:1} : {}) Commented Jan 15, 2017 at 7:33
  • Thanks for the suggestion, but it's more or less the same and a lot longer. Commented Jan 15, 2017 at 7:33
  • 1
    @simonzack yeah except spread syntax for objects is still just a proposal. Commented Jan 15, 2017 at 7:40
  • Is there a relationship between condition and 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. Commented Jan 15, 2017 at 7:42
  • @GantTheWanderer Not really. Indeed the first version is readable enough but I find myself doing this quite often in my code that a very short one would be nice. Commented Jan 15, 2017 at 7:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.