Skip to content
Advertisement

Better way to write spread operator with conditions in javascript

I’m looking for a better way to write the following code:

JavaScript

fromCreatedAt and toCreatedAt are variables that can change and generate a different object.

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.

Advertisement

Answer

You could create objects using shorthand property name and conditionally spread it

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement