1

I have an array of Athletes objects that contain another array of teams objects that particular athlete has played for:

  var athletes = [
  {
    "athlete_id": 123,
    "first_name": "john",
    "last_name": "doe",
    "teams": [
      { "team_id": 4,"team_name": "Eagles" },
      { "team_id": 7, "team_name": "Knights" }
    ]
  },
  {
    "athlete_id": 276,
    "first_name": "jane",
    "last_name": "doe",
    "teams": [
      { "team_id": 4,"team_name": "Pilots" },
      { "team_id": 7, "team_name": "Thunder" }
    ]      
  }
];

I want to, very simply, render the items in this format (teams listed under full name):

John Doe

Eagles

Knights

Jane Doe

Pilots

Thunder

I have tried the following in the render()method:

<View>
        { athletes.map((item, key) => {
          return <Text key={key}>{item.first_name} + " " + {item.last_name}</Text>
            { item.teams.map((unit, key2) => {
              return <Text key={key2}>{unit.team_name}</Text>
            })}

        })} 
</View>

With the above snippet of code, I have only been able to render the full names of both athletes, and not their teams. What can I do to achieve the proper output?

0

1 Answer 1

3

It is because you are returning the item with the first name, last name in it, before your code has chance to return any of the team data:

<View>
    { athletes.map((item, key) => {
      return (
        <View key={key}>
            <Text>{item.first_name} {item.last_name}</Text>
            { item.teams.map((unit, key2) => {
              return <Text key={key2}>{unit.team_name}</Text>
            })}
        </View>
      );
    })} 
</View>
Sign up to request clarification or add additional context in comments.

3 Comments

I am having an issue with using return(); within the map function. [ Error: unexpected token, expected , ]. This is not a problem when I use single line "return … "
My bad, the returned jsx needs a single parent element, edited answer to add top level div.
I was able to get it working by replacing <div> with <View>. I also shifted ' key={key} ' from the <Text> component to the <View> component to resolve a warning that was previously appearing. Appreciating that your answer seems to be the ReactJS equivalent to the solution, I have marked it as the accepted answer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.