Skip to content

Instantly share code, notes, and snippets.

@NyaGarcia
Created September 24, 2019 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NyaGarcia/01e0bbe488f8bdaf76b77857d7a4216c to your computer and use it in GitHub Desktop.
Save NyaGarcia/01e0bbe488f8bdaf76b77857d7a4216c to your computer and use it in GitHub Desktop.
Adding default properties to an array of objects
const pokemon = [
{
name: 'Charmander',
type: 'Fire'
},
{ name: 'Squirtle', type: 'Water', abilities: ['Torrent', 'Rain Dish'] },
{
name: 'Bulbasur',
type: 'Plant'
}
];
function setDefaultAbilities(object) {
const { abilities = [], ...rest } = object;
return { ...rest, abilities };
}
// Applying the setDefaultAbilities function to all the pokemon in the array:
const normalizedPokemon = pokemon.map(pokemon => setDefaultAbilities(pokemon));
console.log(normalizedPokemon);
//Result: [ { name: 'Charmander', type: 'Fire', abilities: [] }, { name: 'Squirtle', type: 'Water', abilities: [ 'Torrent', 'Rain Dish' ] }, { name: 'Bulbasur', type: 'Plant', abilities: [] } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment