Reputation: 594
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.
Upvotes: 0
Views: 790
Reputation: 16122
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>
Upvotes: 1