是否有较短的语法用于在对象中有条件地设置属性?

Sep*_*eed 3 javascript

我正在尝试解决具有形式和功能的此问题。以下是该问题的两个示例,一个功能失调,但具有我想要达到的形式水平,另一个功能正常,但乏味。

const foo = "Spam";
const bar = () => "Ham";
const qux = (bool) => bool ? "Eggs" : "Beans";

// This is roughly the level of succintless I'd like to achieve
function genObjectPretty(request) { 
  return {
    foo: request.foo && foo,
    bar: request.bar && bar(),
    qux: request.qux && qux(true),
  }
}

console.log("BAD results, with SHORT code.  (bar should not be included)")
console.log(genObjectPretty({foo: true, qux: true}));


// This is the working code which I'd like to make less verbose
function genObjectFunctional(request) { 
  const out = {};
  if (request.foo) { out.foo = foo; }
  if (request.bar) { out.bar = bar(); }
  if (request.qux) { out.qux = qux(true); }
  return out;
}

console.log("GOOD results, but LONG code")
console.log(genObjectFunctional({foo: true, qux: true}));
Run Code Online (Sandbox Code Playgroud)

上面的示例是我正在做的事情的简短版本,仅包含3个属性。在实践中,我还有更多,所以数量if(thing) { this = that }越来越...不是一发不可收拾,而是丑陋。我希望它看起来不那么毛茸茸。

无论如何,有没有条件不设置对象属性的js技巧?

我愿意使用辅助函数,或者最后有几行。就像我说的,实际上,我要清理的不仅仅是3条线。

Nin*_*olz 5

您可以传播undefined/ false或使用具有所需属性/值的对象。结果要么是没有属性,要么是具有值的所需属性。

function genObjectPretty(request) { 
    return {
        foo: request.foo && foo,
        ...request.bar && { bar: bar() },
        qux: request.qux && qux(true),
    };
}

const foo = "Spam";
const bar = () => "Ham";
const qux = (bool) => bool ? "Eggs" : "Beans";

console.log(genObjectPretty({ foo: true, qux: true }));
Run Code Online (Sandbox Code Playgroud)