在Javascript中,如何有条件地将成员添加到对象? [英] In Javascript, how to conditionally add a member to an object?
问题描述
我想创建一个有条件添加成员的对象。
简单的方法是:
I would like to create an object with a member added conditionally. The simple approach is:
var a = {};
if (someCondition)
a.b = 5;
现在,我想写一个更惯用的代码。我正在尝试:
Now, I would like to write a more idiomatic code. I am trying:
a = {
b: (someCondition? 5 : undefined)
};
但现在, b
是其成员 a
,其值为 undefined
。这不是理想的结果。
But now, b
is a member of a
whose value is undefined
. This is not the desired result.
是否有方便的解决方案?
Is there a handy solution?
更新
我寻求一个可以处理几个成员的一般情况的解决方案。
I seek for a solution that could handle the general case with several members.
a = {
b: (conditionB? 5 : undefined),
c: (conditionC? 5 : undefined),
d: (conditionD? 5 : undefined),
e: (conditionE? 5 : undefined),
f: (conditionF? 5 : undefined),
g: (conditionG? 5 : undefined),
};
推荐答案
在纯粹的Javascript中,我想不出任何更具风格的东西比你的第一个代码片段。
In pure Javascript, I cannot think of anything more idiomatic than your first code snippet.
然而,如果使用jQuery库并不是不可能的话,那么 $ .extend()应该符合您的要求,因为文档说:
If, however, using the jQuery library is not out of the question, then $.extend() should meet your requirements because, as the documentation says:
未复制未定义的属性。
Undefined properties are not copied.
因此,您可以写:
var a = $.extend({}, {
b: conditionB ? 5 : undefined,
c: conditionC ? 5 : undefined,
// and so on...
});
并获得您期望的结果(如果 conditionB
false
,然后 b
将不存在于 a
中)。
And obtain the results you expect (if conditionB
is false
, then b
will not exist in a
).
这篇关于在Javascript中,如何有条件地将成员添加到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!