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

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

当前回答

使用lodash库,您可以使用_.omitBy

var a = _.omitBy({
    b: conditionB ? 4 : undefined,
    c: conditionC ? 5 : undefined,
}, _.IsUndefined)

当您有可选的请求时,这会非常方便

var a = _.omitBy({
    b: req.body.optionalA,  //if undefined, will be removed
    c: req.body.optionalB,
}, _.IsUndefined)

其他回答

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

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

如果目标是让对象看起来是自包含的,并且在一组大括号中,你可以尝试这样做:

var a = new function () {
    if (conditionB)
        this.b = 5;

    if (conditionC)
        this.c = 5;

    if (conditionD)
        this.d = 5;
};

我会这样做

var 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

const obj = {
   ...(condition) && {someprop: propvalue},
   ...otherprops
}

现场演示:

Const obj = { (true) && {someprop: 42}, …(false) && {nonprop: "foo"}, …({})&&{狡猾的:"hello"}, } console.log (obj);