crashdaddy

Jul 12, 2020

3 min read

Manipulating Array Elements During Mapping in React

If only they had some kind of identification

Problem:

The Example:

{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "http://swapi.co/api/planets/1/",
"films": [
"http://swapi.co/api/films/2/",
"http://swapi.co/api/films/6/",
"http://swapi.co/api/films/3/",
"http://swapi.co/api/films/1/",
"http://swapi.co/api/films/7/"
],
"species": [
"http://swapi.co/api/species/1/"
],
"vehicles": [
"http://swapi.co/api/vehicles/14/",
"http://swapi.co/api/vehicles/30/"
],
"starships": [
"http://swapi.co/api/starships/12/",
"http://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "http://swapi.co/api/people/1/"
}

What We’re Tryna Do:

How We Been Doing It:

INB4 “them aren’t people” — I told you the API was down right now
{this.props.ship.people && this.props.ship.people.map(person => <Link to={{ "pathname": `/people/` }}> 
<span>{person.name}</span>
<img src={`${person.imgPath}`} />
</Link>
)}

What We Shoulda Had Been Doing:

{this.props.ship.people && this.props.ship.people.map(person=> {let idStr = person.url.split('/');
let personID = idStr[5];
return (<Link to={{ "pathname": `/people/${personID}` }}>
<img src={`${person.imgPath'}`}/>
</Link>
)})}
<Link to={{ "pathname": `/people/${personID}` }}>

That’s All. Go Home.