I'm trying to achieve a solution to this problem that has both form and function. Below are two examples of the problem, one is dysfunctional but has the level of form I'd like to achieve, and the other is functional but tedious.
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}));
The example above is a very shortened version of what I'm doing, including only 3 properties. In practice, I have many more, so the amount of if(thing) { this = that }
is getting... not out of hand, but ugly. I'd like it to be less hairy looking.
Anyways, are there any js tricks for conditionally not setting properties of an object?
I'm open to using helper functions, or having a few lines at the end. Like I said, in practice, it's not just 3 lines I'm trying to clean up.