I’m looking for a better way to write the following code:
JavaScript
x
18
18
1
let fromCreatedAt;
2
let toCreatedAt = new Date();
3
4
const someObject = {
5
!!fromCreatedAt || !!toCreatedAt) ? { ((
6
createdAt: {
7
!!fromCreatedAt ? { (
8
from: fromCreatedAt,
9
} : {}),
10
!!toCreatedAt ? { (
11
to: toCreatedAt,
12
} : {}),
13
},
14
} : {}),
15
}
16
17
console.log(someObject); // { createdAt: { to: 2020-11-18T05:32:57.697Z } }
18
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
1
14
14
1
let fromCreatedAt,
2
toCreatedAt = new Date(),
3
from = fromCreatedAt,
4
to = toCreatedAt;
5
6
const createdAt = {
7
from && { from }), (
8
to && { to }) (
9
},
10
someObject = {
11
from || to && { createdAt }) (
12
}
13
14
console.log(someObject)