我想创建一个对象,有条件地添加成员。
简单的方法是:
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),
};
性能测试
经典的方法
const a = {};
if (someCondition)
a.b = 5;
VS
展开算子法
const a2 = {
...(someCondition && {b: 5})
}
结果:
经典的方法要快得多,所以要考虑到语法糖化更慢。
testClassicConditionFulfilled ();// ~ 234.9ms
testClassicConditionNotFulfilled ();/ / ~ 493 1ms。
testSpreadOperatorConditionFulfilled ();/ / ~紧密4ms。
testSpreadOperatorConditionNotFulfilled ();/ / ~ 2239。卫生组织
function testSpreadOperatorConditionFulfilled() {
const value = 5;
console.time('testSpreadOperatorConditionFulfilled');
for (let i = 0; i < 200000000; i++) {
let a = {
...(value && {b: value})
};
}
console.timeEnd('testSpreadOperatorConditionFulfilled');
}
function testSpreadOperatorConditionNotFulfilled() {
const value = undefined;
console.time('testSpreadOperatorConditionNotFulfilled');
for (let i = 0; i < 200000000; i++) {
let a = {
...(value && {b: value})
};
}
console.timeEnd('testSpreadOperatorConditionNotFulfilled');
}
function testClassicConditionFulfilled() {
const value = 5;
console.time('testClassicConditionFulfilled');
for (let i = 0; i < 200000000; i++) {
let a = {};
if (value)
a.b = value;
}
console.timeEnd('testClassicConditionFulfilled');
}
function testClassicConditionNotFulfilled() {
const value = undefined;
console.time('testClassicConditionNotFulfilled');
for (let i = 0; i < 200000000; i++) {
let a = {};
if (value)
a.b = value;
}
console.timeEnd('testClassicConditionNotFulfilled');
}
testClassicConditionFulfilled(); // ~ 234.9ms
testClassicConditionNotFulfilled(); // ~493.1ms
testSpreadOperatorConditionFulfilled(); // ~2649.4ms
testSpreadOperatorConditionNotFulfilled(); // ~2278.0ms