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?
Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
Object Property Initializer Before ES6, the object literal is a collection of name-value pairs. For example, In ES5. function user(name, division) { return {
Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.
Optional chaining (?.) The optional chaining operator ( ?. ) accesses an object's property or calls a function. If the object is undefined or null , it returns undefined instead of throwing an error.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With