Conditionally set an object property

Use the spread operator.

data: {
    userId: 7,
    actionId: 36,
    ...myCondition && {express: true}
}

Note that if you’re using Flow, that syntax might generate type check errors. You can write the above more explicitly, and less succinctly, as:

data: {
    userId: 7,
    actionId: 36,
    ...(myCondition ? {express: true} : {})
}

Leave a Comment