使用 javascript 中的条件编写扩展运算符的更好方法
Better way to write spread operator with conditions in javascript
我正在寻找一种更好的方法来编写以下代码:
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 字段条件的对象,因此您会找到一种方法来重构重复的功能。
我将使用 shorthand 属性创建 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);
我认为这可能更优雅一些,但它并没有消除重复条件,所以可能没有完全回答问题。
您可以使用 shorthand property name 创建对象并有条件地传播它
let fromCreatedAt,
toCreatedAt = new Date(),
from = fromCreatedAt,
to = toCreatedAt;
const createdAt = {
...(from && { from }),
...(to && { to })
},
someObject = {
...(from || to && { createdAt })
}
console.log(someObject)
我正在寻找一种更好的方法来编写以下代码:
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 字段条件的对象,因此您会找到一种方法来重构重复的功能。
我将使用 shorthand 属性创建 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);
我认为这可能更优雅一些,但它并没有消除重复条件,所以可能没有完全回答问题。
您可以使用 shorthand property name 创建对象并有条件地传播它
let fromCreatedAt,
toCreatedAt = new Date(),
from = fromCreatedAt,
to = toCreatedAt;
const createdAt = {
...(from && { from }),
...(to && { to })
},
someObject = {
...(from || to && { createdAt })
}
console.log(someObject)