Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 271
Andrew Mao Avatar asked Dec 19 '17 17:12

Andrew Mao


People also ask

What is the correct syntax for declaring an object literal?

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.

What is object literal in ES6?

Object Property Initializer Before ES6, the object literal is a collection of name-value pairs. For example, In ES5. function user(name, division) { return {

What is object keys in JavaScript?

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.

What is optional chaining in JavaScript?

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.


1 Answers

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);
like image 62
Ori Drori Avatar answered Sep 21 '22 07:09

Ori Drori