0

I am trying to map over specific values in an array of objects. I have collected data from my Backend API and this is the response:

// An array of objects
console.log(response.data) = 
[
    {name:"Bryan",age:"25",sport:"basketball"},
    {name:"Justin",age:"30",sport:"soccer"},
    {name:"Mark",age:"28",sport:"basketball"},
    {name:"Cowell",age:"27",sport:"soccer"},
]

I put this data into a state ("data") using "useState()" from React and used a useEffect to unpack the data upon rendering.

const [data, setData] = useState([])

// some function to store response.data in state
setData(response.data)

I want to map these values onto my Browser in the following way such that Soccer players are displayed in the first div and Basketball players in the second div: (tried several ways but they resulted in parsing errors)

function App() {
    const [data, showData] = useState([])

    return (
      <div>
         {data.map(info => {
              <div>
                 <h1> Sport: soccer </h1> 
                 <h5> {info.name} </h5>
              </div>

              <div>
                 <h1> Sport: basketball</h1> 
                 <h5> {info.name} </h5>
              </div>
           }
         )}
      </div>
    )
}

I am trying to group the names within the same div block (same sport) and not 2 different div blocks for each sport.

2
  • You're not returning anything from the map Commented Jul 30, 2022 at 7:18
  • It does return but it returns all their names instead of the specific category "Soccer" and "Basketball". Commented Jul 30, 2022 at 7:21

1 Answer 1

1

You need to return the elements from the map function and also remove the part where you hardcode basketball.

{data.map((info, idx) => (
  <div key={idx}>
    <h1> Sport: {info.sport} </h1>
    <h5> {info.name} </h5>
  </div>
))}

const groupBy = (array, getGroupByKey) => {
  return (
    (array &&
      array.reduce((grouped, obj) => {
        const groupByKey = getGroupByKey(obj);

        if (!grouped[groupByKey]) {
          grouped[groupByKey] = [];
        }

        grouped[groupByKey].push(obj);

        return grouped;
      }, {})) ||
    {}
  );
};

const App = (props) => {
  var [data, setData] = React.useState([
    { name: 'Bryan', age: '25', sport: 'basketball' },
    { name: 'Justin', age: '30', sport: 'soccer' },
    { name: 'Mark', age: '28', sport: 'basketball' },
    { name: 'Cowell', age: '27', sport: 'soccer' },
  ]);

  const players = groupBy(data, (player) => player.sport);
  const sportKeys = Object.keys(players);



  return (
    <div>
      {sportKeys.map((info, idx) => (
        <div key={idx}>
          <h1> Sport: {info} </h1>
          {players[info].map((player, i) => (
            <h5 key={i}>{player.name}</h5>
          ))}
        </div>
      ))}
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

This works! However, I am trying to group the names within the same div block (same sport). This creates 2 div blocks for each sport.
You need to group the data first then display it. I've updated my answer.

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.