Reputation: 20416
I have a property bar
that can be undefined
or null
const result = {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
bar: await some?.http?.request?.that?.can?.be?.undefined?.or?.null
}
// outputs this
const result: {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
bar: undefined /// -> How to prevent this from being added
}
I know I can do this
const result: {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
}
const bar = await some?.http?.request?.that?.can?.be?.null?.or?.undefined
if (bar != null) {
result.bar = bar
}
But is there a shorter (syntax) way ?
Also, this approach would not work if result
is meant to be immutable
once it is defined
Upvotes: 0
Views: 530
Reputation: 2946
You could as well decide on a later step what to do:
result = Object.fromEntries(Object.entries(result).filter( ([_,v]) => ( v!= null)))
And if the object is inmutable, you can just create a new one:
const defResult = Object.fromEntries(Object.entries(result).filter( ([_,v]) => ( v!= null)))
But i'm afraid of that is not "shorter" as you asked
Upvotes: 2
Reputation: 50749
You can conditionally add bar
by firstly computing the value of bar
(like you have in your second example):
const bar = await some?.http?.request?.that?.can?.be?.undefined?.or?.null
Then when you create result
you use the ternary conditional operator to return an object with {bar: <value>}
or an empty object {}
, which you can then merge into the result object using the spread syntax:
const bar = await some?.http?.request?.that?.can?.be?.undefined?.or?.null
const result = {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
...(bar != null ? {bar} : {})
}
See examples below:
const bar1 = null;
const result1 = {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
...(bar1 != null ? {bar: bar1} : {})
};
console.log("bar 'null':", result1);
const bar2 = undefined;
const result2 = {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
...(bar2 != null ? {bar: bar2} : {})
};
console.log("bar 'undefined':", result2);
const bar3 = "foo4";
const result3 = {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
...(bar3 != null ? {bar: bar3} : {})
};
console.log("bar 'foo4':", result3);
Upvotes: 4
Reputation: 2292
You can encapsulate it in function to handle it more appropriately with ternary operator. The ternary operator will make sure that you don't get null or undefined.
const result: {
foo1: 'foo1',
foo2: 'foo2',
foo3: 'foo3',
bar: function(){
const bar = await request();
return (bar !== null || bar !== undefined)? bar: {};
}
}
Upvotes: 0