我想创建一个对象,有条件地添加成员。
简单的方法是:
var a = {};
if (someCondition)
a.b = 5;
现在,我想写一个更习惯的代码。我在努力:
a = {
b: (someCondition? 5 : undefined)
};
但是现在,b是a的一个元素,它的值是未定义的。这不是我们想要的结果。
有没有方便的解决办法?
更新
我寻求一个解决方案,可以处理一般情况与几个成员。
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),
};
用let定义一个变量,然后赋值一个新属性
let msg = {
to: "hito@email.com",
from: "hifrom@email.com",
subject: "Contact form",
};
if (file_uploaded_in_form) { // the condition goes here
msg.attachments = [ // here 'attachments' is the new property added to msg Javascript object
{
content: "attachment",
filename: "filename",
type: "mime_type",
disposition: "attachment",
},
];
}
现在味精变成了
{
to: "hito@email.com",
from: "hifrom@email.com",
subject: "Contact form",
attachments: [
{
content: "attachment",
filename: "filename",
type: "mime_type",
disposition: "attachment",
},
]
}
在我看来,这是一个非常简单易行的解决方案。
我认为你第一个有条件地增加成员的方法是完全没问题的。我不同意不让元素b (a)的值为undefined。使用带有in操作符的for循环来添加一个未定义的检查非常简单。但无论如何,你可以很容易地编写一个函数来过滤掉未定义的成员。
var filterUndefined = function(obj) {
var ret = {};
for (var key in obj) {
var value = obj[key];
if (obj.hasOwnProperty(key) && value !== undefined) {
ret[key] = value;
}
}
return ret;
};
var a = filterUndefined({
b: (conditionB? 5 : undefined),
c: (conditionC? 5 : undefined),
d: (conditionD? 5 : undefined),
e: (conditionE? 5 : undefined),
f: (conditionF? 5 : undefined),
g: (conditionG? 5 : undefined),
});
还可以使用delete操作符就地编辑对象。
在纯Javascript中,我想不出比第一个代码片段更习惯的东西了。
但是,如果使用jQuery库不是不可能的,那么$.extend()应该可以满足您的需求,因为正如文档所述:
未定义的属性不会被复制。
因此,你可以这样写:
var a = $.extend({}, {
b: conditionB ? 5 : undefined,
c: conditionC ? 5 : undefined,
// and so on...
});
并获得您期望的结果(如果条件b为假,则b将不存在于a中)。
用let定义一个变量,然后赋值一个新属性
let msg = {
to: "hito@email.com",
from: "hifrom@email.com",
subject: "Contact form",
};
if (file_uploaded_in_form) { // the condition goes here
msg.attachments = [ // here 'attachments' is the new property added to msg Javascript object
{
content: "attachment",
filename: "filename",
type: "mime_type",
disposition: "attachment",
},
];
}
现在味精变成了
{
to: "hito@email.com",
from: "hifrom@email.com",
subject: "Contact form",
attachments: [
{
content: "attachment",
filename: "filename",
type: "mime_type",
disposition: "attachment",
},
]
}
在我看来,这是一个非常简单易行的解决方案。