I have the following response data:
{name: "some Name", hobbies: Array(13), others: Array(17)}
.
I want to display the received data as following:
Name -- represented as a simple paragraph.
Hobbies - represented as an accordion of hobbies
beneath the Name - Where the title of the each accordion is the first word within the respective hobby array entry and the body is the whole array entry.
Others - represented again as a simple paragraph, which lists each of the values within the others array beneath the Hobbies.
I have tried the multiple approaches to access the elements but to no avail. So far I get results with the following but they are far from what I expect to have. Please assume that results contains the response that I have gotten using axios.post and sending the request to my API.
<div className="searchResults">
{Object.entries(results).map(([key, value]) =>
Object.entries(value).map(([index, value1]) =>
<p key={index}>
{value1}
</p>
))}
</div>
If I understood correctly, the results
contains the object, e.g. {name: "some Name", hobbies: Array(13), others: Array(17)}
.
If so, you wrongly iterate over the results
.
The solution is:
{Object.keys(results).length && (
<div className="results">
<p>{results.name}</p>
<Accordion defaultActiveKey="0" style={{width: '80%'}}>
{Object.entries(results.hobbies).map(([key, value]) =>
<Card key={key}>
<Accordion.Toggle as={Card.Header} eventKey="1">
{key}
</Accordion.Toggle>
<Accordion.Collapse eventKey="1">
<Card.Body>
{value}
</Card.Body>
</Accordion.Collapse>
</Card>
)}
</Accordion>
{Object.entries(results.others).map(([key, value]) =>
<p>{value}</p>
)}
</div>
)}