How can one create or not create object properties that are dependent on some condition. For example one can define a variable that's dependent on some condition by doing:
const foo = someCondition ? true : undefined
However what I'd like to do is the following in pseudo code:
const foo = {
someCondition ? { a: true }
b: 'b'
}
// returning { a: true, b: 'b' } if someCondition or { b: 'b'} if not.
One way to solve this is via:
const foo = { ...someCondition ? { a: true }: {}, ...{ b: 'b'} }
However this doesn't seems like a great solution to me as it requires the creation of a bunch of intermediate objects and then merging them into a new object - which won't be performant.
Another solution is:
const foo = { b: 'b'}
if(someCondition) foo.a = true
Which is okayish, however it splits object creation into two or more distinct steps, which I also don't like.
And another solution:
const foo = { b: 'b'}
if(someCondition) Object.defineProperty(foo,'a',{ value: true})
Similar to the solution above.
Perhaps one of you has found a better way to do this than I have?
Using prototypes you could do it like so:
let myBool = true;
function Obj() {
if (myBool) this.myConditionedProp = "5"
}
let myObj = new Obj()
You can also directly pass parameters in the prototype function:
function Obj(age) {
this.name = 'John'
if(age) this.age = age
}
let myObj = new Obj(15)
console.log(myObj.name, myObj.age)
This method have the merit not to split the object creation, despite not really providing more simplicity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With