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

此生再无相见时 提交于 2020-06-17 09:50:07

问题


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?


回答1:


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



回答2:


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



回答3:


the following pattern is common in Javascript

It should not. Having many objects of different shapes can incur a performance penalty. Records should always contain the same keys. So just use

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


来源:https://stackoverflow.com/questions/62214748/how-to-create-an-object-with-a-conditional-computed-property-name-in-a-one-liner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!