有条件地设置对象属性 [英] Conditionally set an object property
问题描述
是否有一些基于条件设置属性的语法?
Is there some syntax for setting properties based on a condition?
data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : null) // does not work
}
我希望 express
设置为一个值或者根本不设置(即,应该没有名为<$ c的键$ c> express ),定义后没有额外的陈述。我知道我可以将它用作布尔值,但接收端使用 isset()
检查,我想知道是否可以避免修改它。
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):
JSON.stringify (Chris Kessel, dystroy):
var json = JSON.stringify( {
data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : null)
}
});
匿名函数(Paulpro):
An anonymous function (Paulpro):
var data = new function(){
this.userId = 7;
this.actionId = 36;
myCondition && (this.express = true);
};
额外声明(x4rf41):
data: {
userId: 7,
actionId: 36
}
if(myCondition) data["express"] = true;
Eval (我以前的同事):
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 })
);
推荐答案
这样做:
data: {
userId: 7,
actionId: 36,
express: (myCondition ? true : undefined)
}
价值未定义的物业$ c当您 stringify 对象时,不会写入$ c>到JSON。
A property whose value is undefined
isn't written when you stringify the object to JSON.
编辑:从评论中可以看出,实际上没有涉及JSON。 OP使用 $ .ajax
因此可能使用 $ .param
。不幸的是, $ .param
确实为值为 undefined
的属性创建了一个条目。所以没有任何补充代码行可能没有解决方案。
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.
这篇关于有条件地设置对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!