Succinct/concise syntax for 'optional' object keys in ES6/ES7?
To indicate optional
key, you can assign to it null
, if the condition is false
const someCondition = true;
const obj = {
requiredKey1: 1,
requiredKey2: 2,
optionalKey1: someCondition ? 'optional' : null
};
console.log(obj);
You can use object spread to have an optional property:
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);