0

I'm aware with ES6 JavaScript object you can dynamically declare variables as object keys, using [], for example:

{[2 + 2]: "four!"}

gives the output {"4": "four!"}

the question is, can a similar method be done in order to add an entire property, through variables etc., inline? Meaning, like suppose I have the following test object:

var myObj = {
    someProp: 2,
    someOtherProp: 3 //only add this prop if a condition is met
}

is there anything I can write in the inline object for someOtherProp, to only have it be added to the object, if a certain condition is met? So for example (pseudocode), something like this

var myObj = {
    someProp: 2,
    [someBool ? null : "someOtherProp: 3"] //only add this prop if a condition is met
}

would give the ouput (considering someBool is true), like the above, but if someBool is false, it would give me

var myObj = {
    someProp: 2
}

??

I'm aware I can simply add a property (or delete one) to (/from) the object later, using the [] indexer, like

someBool && (myObj["someOtherProp"] = 3)

as well as make some kind of helper function for this,

but I was wondering if there was a way to do it using the inline-object notation?

2

1 Answer 1

8

You could spread an object with a conditional operator.

{} is a neutral value.

var myObj = {
    someProp: 2,
    ...(someBool ? {} : { someOtherProp: 3 })
}
Sign up to request clarification or add additional context in comments.

1 Comment

That could be even shorter with ...(someBool && { someOtherProp: 3})

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.