Using JavaScript’s map function

Written by daveford | Published 2017/04/22
Tech Story Tags: javascript | react

TLDRvia the TL;DR App

The map function simply transforms one array into another array. For example, suppose you have an array of person objects but what you really need is an array of names (strings):

The map function will convert the array of person objects into an array of names (strings).

Lets say this is the array you start with:

const friends = [{id:1, name: 'Dave',age:50},{id:2,name: 'Kellie',age:42},{id:3,name: 'Max',age:12},{id:2,name: 'Jack',age:12}];

and you want to convert it to this:

['Dave', 'Kellie', 'Max','Jack']

You start by defining a mapping function. The mapping function operates on a single row, converting (or mapping) one person into one name (string):

const mappingFunction = p => p.name;

Then you pass the mapping function to array.map like this:

const names = friends.map(mappingFunction);

which returns:

['Dave', 'Kellie', 'Max','Jack']

You can also do this as a one liner:

const names = friends.map(p => p.name);

Map function in React JSX

This type of thing is very common in React JSX. To map an array of person objects to an array of <li> elements, use a mapping function like this:

const mappingFunction = p => <li>{p.name}</li>;

To ensure React’s DOM diff’ing works correctly, you’ll need to provide each <li> with a unique key:

const mappingFunction = p => <li key={p.id}>{p.name}</li>;

In context, this might look something like this:

render(){return <ul>{friends.map(p => <li key={p.id}>{p.name}</li>)}</ul>;}


Published by HackerNoon on 2017/04/22