Skip to content

Instantly share code, notes, and snippets.

@micahriggan
Last active March 28, 2019 17:31
Show Gist options
  • Save micahriggan/bee11c78b6575c4d11c45ea7b5e9d663 to your computer and use it in GitHub Desktop.
Save micahriggan/bee11c78b6575c4d11c45ea7b5e9d663 to your computer and use it in GitHub Desktop.
adding conditional properties to objects using ...bool && object

Javascript Property Wizardry

Did you know you can add properties conditionally to an object with spread?

so instead of

function getUser(banned) {
  const userStatus = {banned, banReason: 'Wizard'};
  // only combine the user status if the user is banned
  const user = { name: 'Micah' };
  if(userStatus.banned) {
    Object.assign(user, userStatus);
  }
   return user;
}


console.log(getUser(true));
console.log(getUser(false));

you can do

function getUser(banned) {
  const userStatus = {banned, banReason: 'Wizard'};
  // only combine the user status if the user is banned
   return {
    name: 'Micah',
    ...userStatus.banned && userStatus,
  }
}


console.log(getUser(true));
console.log(getUser(false));

Outputs

{ name: 'Micah', banned: true, banReason: 'Wizard' }
{ name: 'Micah' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment