Conditionally set an object property
javascript
Solution
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.
Problem
Is there some syntax for setting properties based on a condition? ``` data: { userId: 7, actionId: 36, express: (myCondition ? true : null) // does not work } ``` I want `express` to be either set to a value or not set at all (i.e., there should be no key named `express`), and without extra statements after the definition. I know I can use it as a boolean, but the receiving side is using an `isset()` check and I'm wondering if I can avoid modifying it. Edit: Seems there is no direct solution to the problem as stated. Here are the close suggestions: JSON.stringify (Chris Kessel, dystroy): ``` var json = JSON.stringify( { data: { userId: 7, actionId: 36, express: (myCondition ? true : null) } }); ``` An anonymous function (Paulpro): ``` var data = new function(){ this.userId = 7; this.actionId = 36; myCondition && (this.express = true); }; ``` An extra statement (x4rf41): ``` data: { userId: 7, actionId: 36 } if(myCondition) data["express"] = true; ``` Eval (a former colleague of mine): ``` eval("data = {userId: 7, actionId: 36 " + (myCondition ? ", express: true}" : "}")) ``` Conditional definition (don't really know how to label this one): ``` data = ( (myCondition && { userId: 7, actionId: 36, express: true }) || (!myCondition && { userId: 7, actionId: 36 }) ); ```