Is there a more efficient way to create object properties that are dependent on certain conditions? For example, one can define a variable based on a condition like this:
const foo = someCondition ? true : undefined
However, what I am seeking is to achieve something like the following in pseudo code:
const foo = {
someCondition ? { a: true }
b: 'b'
}
// returning { a: true, b: 'b' } if someCondition is met or { b: 'b'} if not.
One approach to tackle this is through:
const foo = { ...someCondition ? { a: true }: {}, ...{ b: 'b'} }
Nevertheless, I find this solution involving the creation of intermediate objects and their merging into a new object to be suboptimal in terms of performance.
Another option could be:
const foo = { b: 'b'}
if(someCondition) foo.a = true
This method, while functional, separates the process of object creation into multiple steps, which is not ideal.
Yet another possibility:
const foo = { b: 'b'}
if(someCondition) Object.defineProperty(foo,'a',{ value: true})
Similar to the previous solution.
I'm curious if any of you have discovered a better way to accomplish this task than the ones I have tried?