javascript ES6/ES7 中“可选”对象键的简洁/简洁语法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47892127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Succinct/concise syntax for 'optional' object keys in ES6/ES7?
提问by Andrew Mao
There are already a lot of cool featuresin ES6/ES7 for defining Javascript objects. However, the following pattern is common in Javascript:
ES6/ES7中已经有很多很酷的特性来定义 Javascript 对象。但是,以下模式在 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?
有没有办法用可选和必需的键一次定义对象?
回答by Ori Drori
You can use object spreadto have an optional property.
您可以使用object spread来拥有一个可选属性。
Note:Object Rest/Spread is a stage 4 proposal for ECMAScript. You might need the babel transformto use it.
注意:Object Rest/Spread 是 ECMAScript 的第 4 阶段提案。您可能需要babel 转换才能使用它。
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);
回答by Suren Srapyan
To indicate optionalkey, you can assign to it null, if the condition is false
要指示optional键,您可以分配给它null,如果条件为假
const someCondition = true;
const obj = {
requiredKey1: 1,
requiredKey2: 2,
optionalKey1: someCondition ? 'optional' : null
};
console.log(obj);
回答by Bergi
the following pattern is common in Javascript
以下模式在 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,
};

