Add conditional properties in JS objects


How conditionaly add properties to object?

As it turned out, it's pretty simple:




const user = { id: 1, name: 'Suhomozgy Andrey' }

const position = 'Frontend Developer'

const userWithPosition = {

  ...user,

  id: 2,

  ...(position && { position })

}



userWithPosition //=> { id: 2, name: 'Suhomozgy Andrey', position: 'Frontend Developer' }






Suhomozgy
Andrey

at JetRockets

Explore more of JetRockets