0

I have looked for an answer to this and Haven't quite been able to find it. Is it possible to have an object that includes/excludes keys dynamically?

Consider these two examples:

Example 1

const name = 'Garrett'
const city = 'Miami'

const obj = {
    name: name,
    city: city
}

console.log(obj) // { name: 'Garrett', city: 'Miami' }

Example 2

const name = 'Garrett'
const city = ''

const obj = {
    name: name,
    city?: city // Something like adding a "?"
}

console.log(obj) // { name: 'Garrett' }

If city is an empty string I don't want it to exist in the object at all. I understand that I can use a ternary, however in that case the key is still on the object just with a value of undefined, which I don't want. Sure I could check after creating the object, but that seems like a waste if there is a way of doing at the time of creation.

Garrett
  • 1,576
  • 4
  • 27
  • 51

0 Answers0