简体   繁体   English

在javascript中使用条件编写扩展运算符的更好方法

[英]Better way to write spread operator with conditions in javascript

I'm looking for a better way to write the following code:我正在寻找一种更好的方法来编写以下代码:

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 and toCreatedAt are variables that can change and generate a different object. fromCreatedAt 和 toCreatedAt 是可以更改和生成不同对象的变量。

This is just an example, but you could have an object that repeats the conditions of the createdAt field multiple times for other fields, so you would find a way to refactor that repeated functionality.这只是一个示例,但您可以拥有一个对象,该对象为其他字段多次重复 createdAt 字段的条件,因此您会找到一种方法来重构重复的功能。

I'd use shorthand properties to create the createdAt nested object, removing undefined values by filtering through Object.fromEntries .我会使用速记属性来创建createdAt嵌套对象,通过过滤Object.fromEntries删除未定义的值。 Then you can create the someObject depending on whether the createdAt object has any keys or not:然后你可以根据createdAt对象是否有任何键来创建someObject

 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);

You could create objects using shorthand property name and conditionally spread it您可以使用速记属性名称创建对象并有条件地传播它

 let fromCreatedAt, toCreatedAt = new Date(), from = fromCreatedAt, to = toCreatedAt; const createdAt = { ...(from && { from }), ...(to && { to }) }, someObject = { ...(from || to && { createdAt }) } console.log(someObject)

Because ...null and ...undefined will cause no data properties to be copied, you could get rid of the ternary operators and simplify to boolean short-circuit evaluation:因为...null...undefined不会导致任何数据属性被复制,你可以摆脱三元运算符并简化为布尔短路评估:

 let fromCreatedAt; let toCreatedAt = new Date(); const someObject = { ...(fromCreatedAt || toCreatedAt) && { createdAt: { ...fromCreatedAt && { from: fromCreatedAt}, ...toCreatedAt && { to: toCreatedAt}, } } }; console.log(someObject);

I thought this might be a little more elegant, but it doesn't get rid of the duplicate conditions, so probably doesn't answer the question completely.我认为这可能更优雅一些,但它并没有摆脱重复的条件,所以可能没有完全回答这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM