ES6/ES7中“可选”对象键的简洁/简洁语法?

ES6/ES7中已经有很多定义 Javascript 对象的 很酷的特征。然而,以下模式在 Javascript 中很常见:

const obj = {
requiredKey1: ...,
requiredKey2: ...
};


if (someCondition) {
obj.optionalKey1 = ...;
}

有没有一种同时使用可选键和必需键来定义对象的方法?

40389 次浏览

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

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

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,
};