Conditionally Adding Keys to a JavaScript Object

April 28, 2021

const showFirstName = true,
      showMiddleName = false,
      showLastName = true

const user = {
   ...(addFirstName && {firstName: 'Sabin'}),
   ...(addMiddleName && {middleName: 'secret...'}),
   ...(addLastName && {lastName: 'Adams'})
}
{
   "firstName": "Sabin",
   "lastName": "Adams"
}