Using JavaScript’s map function – David Ford – Medium

Using JavaScript’s map function  #react #javascript #reactjs

  • Using JavaScript’s map functionThe map function simply transforms one array into an other 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 = 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 JSXThis 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;}

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

@ReactDOM: Using JavaScript’s map function #react #javascript #reactjs

The map function simply transforms one array into an other 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:

{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):

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

which returns:

[‘Dave’, ‘Kellie’, ‘Max’,’Jack’]

You can also do this as a one liner:

This type of thing is very common in React JSX. To map an array of person objects to an array of

  • elements, use a mapping function like this:

    To ensure React’s DOM diff’ing works correctly, you’ll need to provide each

  • with a unique key:

    In context, this might look something like this:

  • Using JavaScript’s map function – David Ford – Medium