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.
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.