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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
janpauldahlke profile image
jan paul

with nullguard

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

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay