Better way to write spread operator with conditions in javascript

Tags: , , ,



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.

Answer

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)


Source: stackoverflow