The map()
array method in JavaScript manipulates an array and returns a new array with the altered data.
Example 1
Let's say we have an array of objects called dogs
const dogs = [
{
name: "Scruffy",
breed: "Labrador",
age: 3,
likes: ["being a good boi", "walks"],
},
{
name: "Shandy",
breed: "Bulldog",
likes: ["sticks", "treats"],
},
]
Let's say we want a new array from dogs showing just the dog breeds available.
const breeds = dogs.map(dog => dog.breed)
// [ 'Labrador', 'Bulldog' ]
We map
over dogs and for each dogs available we add the breed to our new array.
Example 2
In this example we want to return a new array of objects, of each dogs name and what the dogs likes.
const nameAndLikes = dogs.map(dog => {
return {
name: dog.name,
likes: dog.likes,
}
})
/*[
{
name: 'Scruffy',
likes: [ 'being a good boi', 'walks' ]
},
{ name: 'Shandy',
likes: [ 'sticks', 'treats' ]
}
] */
This time we set the keys we want and then set the values to dog.name
and dog.likes
. Remember this returns a new array and doesn't alter the original.
Top comments (1)
Additional things to look at for beginners:
filter()
reduce()
Object:
Set()