Conditionally set an object property
Solution 1:
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} : {})
}
Solution 2:
Do it like this :
data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : undefined)
}
A property whose value is undefined
isn't written when you stringify the object to JSON.
EDIT : It appears from the comments that there is no JSON involved in fact. OP is using $.ajax
so $.param
is probably used. $.param
, unfortunately, does create an entry for properties whose value is undefined
. So there's probably no solution without any supplementary line of code.
Solution 3:
You can do it if you define your object using an anonymous function instead of object literal notation:
var data = new function(){
this.userId = 7;
this.actionId = 36;
myCondition && (this.express = true);
};
The resulting data
object is the exact same, except it's constructor
will be the anonymous function instead of window.Object
.
Solution 4:
You could do something like this:
var json = JSON.stringify( {
data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : null)
}
});
Solution 5:
A bit old but there is a good solution as well you can do :
data: {
userId: 7,
actionId: 36
}
Object.assign(data, !myCondition && { express: yourValue });
Thus it will assign your express property with the value you need if your condition is false.