我想创建一个对象,有条件地添加成员。
简单的方法是:
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",
},
]
}
在我看来,这是一个非常简单易行的解决方案。
使用lodash库,您可以使用_.omitBy
var a = _.omitBy({
b: conditionB ? 4 : undefined,
c: conditionC ? 5 : undefined,
}, _.IsUndefined)
当您有可选的请求时,这会非常方便
var a = _.omitBy({
b: req.body.optionalA, //if undefined, will be removed
c: req.body.optionalB,
}, _.IsUndefined)
我用另一个选项做了一个小的基准测试。我喜欢从一些物体上去除“累赘”。通常是错误的值。
以下是本尼的结果:
清洁
const clean = o => {
for (const prop in o) if (!o) delete o[prop];
}
clean({ value });
传播
let a = {
...(value && {b: value})
};
if
let a = {};
if (value) {
a.b = value;
}
结果
clean : 84 918 483 ops/s, ±1.16% | 51.58% slower
spread : 20 188 291 ops/s, ±0.92% | slowest, 88.49% slower
if : 175 368 197 ops/s, ±0.50% | fastest