我想创建一个对象,有条件地添加成员。 简单的方法是:

var a = {};
if (someCondition)
    a.b = 5;

现在,我想写一个更习惯的代码。我在努力:

a = {
    b: (someCondition? 5 : undefined)
};

但是现在,b是a的一个元素,它的值是未定义的。这不是我们想要的结果。

有没有方便的解决办法?

更新

我寻求一个解决方案,可以处理一般情况与几个成员。

a = {
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
 };

当前回答

我认为@InspiredJW用ES5做到了,正如@trincot指出的那样,使用es6是更好的方法。但我们可以添加更多的糖,通过使用扩散运算符,和逻辑与短路计算:

const a = {
   ...(someCondition && {b: 5})
}

其他回答

性能测试

经典的方法

const a = {};
if (someCondition)
    a.b = 5;

VS

展开算子法

const a2 = {
   ...(someCondition && {b: 5})
}

结果:

经典的方法要快得多,所以要考虑到语法糖化更慢。

testClassicConditionFulfilled ();// ~ 234.9ms testClassicConditionNotFulfilled ();/ / ~ 493 1ms。 testSpreadOperatorConditionFulfilled ();/ / ~紧密4ms。 testSpreadOperatorConditionNotFulfilled ();/ / ~ 2239。卫生组织

function testSpreadOperatorConditionFulfilled() { const value = 5; console.time('testSpreadOperatorConditionFulfilled'); for (let i = 0; i < 200000000; i++) { let a = { ...(value && {b: value}) }; } console.timeEnd('testSpreadOperatorConditionFulfilled'); } function testSpreadOperatorConditionNotFulfilled() { const value = undefined; console.time('testSpreadOperatorConditionNotFulfilled'); for (let i = 0; i < 200000000; i++) { let a = { ...(value && {b: value}) }; } console.timeEnd('testSpreadOperatorConditionNotFulfilled'); } function testClassicConditionFulfilled() { const value = 5; console.time('testClassicConditionFulfilled'); for (let i = 0; i < 200000000; i++) { let a = {}; if (value) a.b = value; } console.timeEnd('testClassicConditionFulfilled'); } function testClassicConditionNotFulfilled() { const value = undefined; console.time('testClassicConditionNotFulfilled'); for (let i = 0; i < 200000000; i++) { let a = {}; if (value) a.b = value; } console.timeEnd('testClassicConditionNotFulfilled'); } testClassicConditionFulfilled(); // ~ 234.9ms testClassicConditionNotFulfilled(); // ~493.1ms testSpreadOperatorConditionFulfilled(); // ~2649.4ms testSpreadOperatorConditionNotFulfilled(); // ~2278.0ms

我认为@InspiredJW用ES5做到了,正如@trincot指出的那样,使用es6是更好的方法。但我们可以添加更多的糖,通过使用扩散运算符,和逻辑与短路计算:

const a = {
   ...(someCondition && {b: 5})
}

下面的代码片段应该可以工作。

const a = {}

const conditionB = true;
const conditionC = true;
const conditionD = true;
const conditionE = true;

const b = {
  ...(conditionB && { b : 5}),
  ...(conditionC && { c : 5}),
  ...(conditionD && { d : 5}),
  ...(conditionE && { e : 5}),
 };

console.log(b);
const isAdult = true;

const obj = {
  ...(isAdult ? { age: 18 }: { age: 17}),
};

//>> { student: 18 }

您可以无条件地添加所有未定义的值,然后使用JSON。Stringify将它们全部删除:

const person = {
  name: undefined,
  age: 22,
  height: null
}

const cleaned = JSON.parse(JSON.stringify(person));

// Contents of cleaned:

// cleaned = {
//   age: 22,
//   height: null
// }