pertrai1 pertrai1 - 1 month ago 15
Javascript Question

Easier JavaScript method names with destructuring

I am trying to find a way so that I can remove the repetitive need for having to use the object name and just the keys. For example:

function(teams) {
return {
teamName: teams.name,
teamCity: teams.city,
teamState: teams.state,
teamMascot: teams.mascot
}
}


It would be nice so that I can have it so that the need to re-use teams each time can be eliminated. Any help would be great.

Answer

You've already mentioned the solution in your title. Just use destructuring.

function logTeam(teams) {
  let { name, city, state, mascot } = teams;
  console.log({
    teamName: name,
    teamCity: city,
    teamState: state,
    teamMascot: mascot
  });
}

logTeam({
  name: 'SO Silverhawks',
  city: 'Interwebs',
  state: 'Earth',
  mascot: 'Stacky'
});

If you want to avoid using the names at all but your properties follow a predictable pattern, you can use Object.keys and work with the keys directly.

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

function createTeam(teams) {
  let result = {};
  Object.keys(teams).forEach(key => {
    result[`team${capitalizeFirstLetter(key)}`] = teams[key];
  });
  return result;
}

console.log(createTeam({
  name: 'SO Silverhawks',
  city: 'Interwebs',
  state: 'Earth',
  mascot: 'Stacky'
}));

capitalizeFirstLetter source