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}));
上面的例子是我正在做的一个非常简短的版本,只包括 3 个属性。在实践中,我有更多,所以数量if(thing) { this = that }
越来越......不是失控,而是丑陋。我希望它看起来不那么毛茸茸。
无论如何,是否有任何 js 技巧可以有条件地不设置对象的属性?
我愿意使用辅助函数,或者在最后写几行。就像我说的,在实践中,我想要清理的不仅仅是 3 行。
解决方案
您可以传播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 }));
推荐阅读
- javascript - 当指针事件在父窗口中没有时如何将焦点设置在子窗口上。JavaScript
- python-3.x - 如何在内部计算 pytorch 中的 autograd.grad?
- python - python为什么对象属性会相互泄漏
- javascript - gapi 客户端 urlshortener url 显示未定义
- oracle - 两列和第三列值的不同值
- nginx - 注释 proxy-body-size 在 kubernete nginx-ingress 中不起作用
- android - 自定义列表视图的问题导致我的应用程序崩溃
- c# - docker 容器下带有 C# 内核的 JupyterHub
- reactjs - 如何使 Material UI 图标表现得像锚标签?
- objective-c - Objective-C 中缺少 JNI 标头