首页 > 解决方案 > 是否有更短的语法来有条件地设置对象中的属性?

问题描述

我正在尝试解决这个问题,它既有形式又有功能。下面是这个问题的两个例子,一个是功能失调但具有我想要达到的形式水平,另一个是功能性但乏味。

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

上面的例子是我正在做的一个非常简短的版本,只包括 3 个属性。在实践中,我有更多,所以数量if(thing) { this = that }越来越......不是失控,而是丑陋。我希望它看起来不那么毛茸茸。

无论如何,是否有任何 js 技巧可以有条件地不设置对象的属性?

我愿意使用辅助函数,或者在最后写几行。就像我说的,在实践中,我想要清理的不仅仅是 3 行。

标签: javascript

解决方案


您可以传播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 }));


推荐阅读