我正在寻找更好的方法来编写以下代码:
let fromCreatedAt;
let toCreatedAt = new Date();
const someObject = {
...((!!fromCreatedAt || !!toCreatedAt) ? {
createdAt: {
...(!!fromCreatedAt ? {
from: fromCreatedAt,
} : {}),
...(!!toCreatedAt ? {
to: toCreatedAt,
} : {}),
},
} : {}),
}
console.log(someObject); // { createdAt: { to: 2020-11-18T05:32:57.697Z } }
fromCreatedAt 和 toCreatedAt 是可以更改并生成不同对象的变量。
这只是一个示例,但您可以有一个对象多次重复其他字段的createdAt字段的条件,因此您会找到一种方法来重构重复的功能。
您可以使用 简写属性名称 创建对象并有条件地传播它
let fromCreatedAt,
toCreatedAt = new Date(),
from = fromCreatedAt,
to = toCreatedAt;
const createdAt = {
...(from && { from }),
...(to && { to })
},
someObject = {
...(from || to && { createdAt })
}
console.log(someObject)
我会使用简写属性来创建
createdAt
嵌套对象,通过过滤 Object.fromEntries
来删除未定义的值。然后,您可以根据 someObject
对象是否有任何键来创建 createdAt
:
let from;
let to = new Date();
const createdAt = Object.fromEntries(
Object.entries({ from, to }).filter(([, val]) => val !== undefined)
);
const someObject = Object.keys(createdAt).length
? { createdAt }
: {};
console.log(someObject);
因为
...null
和...undefined
会导致没有数据属性被复制,你可以摆脱三元运算符并简化为布尔短路评估:
let fromCreatedAt;
let toCreatedAt = new Date();
const someObject = {
...(fromCreatedAt || toCreatedAt) && {
createdAt: {
...fromCreatedAt && { from: fromCreatedAt},
...toCreatedAt && { to: toCreatedAt},
}
}
};
console.log(someObject);
我认为这可能更优雅一点,但它并没有摆脱重复的条件,所以可能没有完全回答问题。