13
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]
Now let's map it
let mapVar = arr.map(data => data * 2)
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'
},
]
console.log(firstArray.map(data => data.name))
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
13