Succinct/concise syntax for 'optional' object keys in ES6/ES7?

Andrew Mao picture Andrew Mao · Dec 19, 2017 · Viewed 19.5k times · Source

There are already a lot of cool features in ES6/ES7 for defining Javascript objects. However, the following pattern is common in Javascript:

const obj = { 
  requiredKey1: ..., 
  requiredKey2: ... 
};

if (someCondition) { 
  obj.optionalKey1 = ...;
}

Is there a way to define the object all at once with both optional and required keys?

Answer

Ori Drori picture Ori Drori · Dec 19, 2017

You can use object spread to have an optional property.

Note: Object Rest/Spread is a stage 4 proposal for ECMAScript. You might need the babel transform to use it.

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 })
};

console.log(obj);