Clear or concise syntax for "optional" object keys in ES6 / ES7?

ES6 / ES7 already has many interesting features 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 an object at the same time as optional and necessary keys?

+10
source share
3 answers

You can use object scatter to have an optional property.

Note: Object Rest / Spread is a Phase 4 sentence for ECMAScript. You may need a 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); 
+22
source

To specify the optional key, you can set it to null if the condition is false

 const someCondition = true; const obj = { requiredKey1: 1, requiredKey2: 2, optionalKey1: someCondition ? 'optional' : null }; console.log(obj); 
+4
source

Javascript typically uses the following pattern:

It does not follow. Having multiple objects of various shapes can result in a performance penalty. Entries must always contain the same keys. Therefore just use

 const obj = { requiredKey1: …, requiredKey2: …, optionalKey1: someCondition ? … : undefined, }; 
0
source

Source: https://habr.com/ru/post/1274197/


All Articles