Dynamic keys in object literals

:wave: Hello. I have a small suggestion.

I find myself doing this many times:

const ssl = !!process.env.SSL
const connectionOptions = {
  url: 'postgresql://...',
  ...ssl && { extra: { ssl: true } }
}

It works but feels a bit intimidating. I think there could be a better alternative:

const ssl = !!process.env.SSL
const connectionOptions = {
  url: 'postgresql://...',
  extra: ssl ? { ssl: true }
}

It is similar to the ternary operator in purpose.

When ssl is true, the result would be:

{ url: 'postgresql://...', extra: { ssl: true } }

When ssl is false, the result would be:

{ url: 'postgresql://...' }

We could also allow a shorter version if the value we want is equal to the condition result:

const cert = fs.writeFileSync(...)
const connectionOptions = {
  url: 'postgresql://...',
  ssl: cert?
}

When ssl is true (would work for any truthy value), the result would be:

{ url: 'postgresql://...', ssl: <cert-content> }

When ssl is a falsy value, the result would be:

{ url: 'postgresql://...' }

@gimenete wouldn't this be a breaking change for apps that have objects using the key "extra"? Maybe this would need some special syntax?

I'd recommend

const connectionOptions = {
  url: 'postgresql://...',
  extra: ssl ? { ssl: true } : undefined,
}

It should be equivalent for all purposes.

This is just an example. It could be extra or it could be anything. The syntax is

key-name: condition ? value

There are circumstances where you don't want an undefined value and you want the key to not be there.