(╯°□°)╯ .map()
The map()
array method manipulates data and returns a new array of changed data.
Example 1
We have an array of objects called dogs.
{
name: "Spike",
age: 5,
vaccinated: true,
breed: "Border Terrier",
likes: ["Being a good boy and eating tripe", "chasing cars"],
},
{
name: "Rex",
age: 8,
vaccinated: true,
breed: "Border Collier",
likes: ["eating sticks on walkies", "attention"],
},
{
name: "Boeta",
age: 12,
vaccinated: false,
breed: "Labrador",
likes: ["running super fast", "napping"],
},
{
name: "Ozzy",
age: 2,
vaccinated: true,
breed: "Chihuahua",
likes: ["barking loudly", "treats"],
},
];
Now, we want to manipulate the data and return a new array with only the dog breeds.
We map
over dogs and for each dog we return their breed to our new array.
const dogBreed = dogs.map((dog) => dog.breed);
// [ "Border Terrier", "Border Collier", "Labrador", "Chihuahua" ]
Example 2
We want to return a new array of both the dogs age and name.
We will map
through dogs and for each dog return their age and name.
const dogNameandAge = dogs.map((dog) => {
return {
name: dog.name,
age: dog.age,
};
});
/*[
{name: "Spike", age: 5}
{ name: "Rex", age: 8 }
{ name: "Boeta", age: 12 }
{ name: "Ozzy", age: 2 }
]*/