DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

3 3

How to use .map() in javascript? React

This is a tutorial for begginers where you will learn how actually use map and how it works.
If you just want to see how to use it go to the bottom.

Let's talk about how .map() works, first of all if you did not know it yet it is a for loop, where it iterate every time there is another object.

What i mean when i said it is a for loop?
I mean that you can actually make a for loop to interate the array or the object you want to iterate.

The map() function basically create a new array with the results of calling a provided function on every element in the calling array.

Let's show an example

let arr = [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

Now let's map it

let mapVar = arr.map(data => data * 2)
Enter fullscreen mode Exit fullscreen mode

Now if we console.log the result we should see all the values multiplied by 2

[2, 4, 6, 8, 10]

Now let's talk about how to map an array of objects which was one of the questions i first had.

First we declare or most commonly will be data from an api which will come in json format but for simplicity i will declare a variable in a 'json format'.

let firstArray = [{
  name: 'uno',
  surname: 'dos'
},{
  name: 'valentina' ,
  surname: 'Gutierrez'
},{
  name: 'Thor',
  surname: 'Suarez'
},
]
Enter fullscreen mode Exit fullscreen mode
console.log(firstArray.map(data => data.name))
Enter fullscreen mode Exit fullscreen mode

That will iterate over every object looking for a name parameter.
In this case the console will print the following

['uno', 'valentina', 'Thor']

Well so that's it for this short article i hope someone find it helpfull
Cheers Lautaro

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (1)

Collapse
 
janpauldahlke profile image
jan paul

with nullguard

console.log((firstdata ?? []).map(data => data.name))

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay