0

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>

1 Answer 1

2

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>
)}
               
Sign up to request clarification or add additional context in comments.

2 Comments

Yes It does look a lot better! Thank you. Can you just tell me what is the purpose of {Object.keys(results).length && ( before the <div className="results">
It is a lazy way of making ternary operator. The <div className="results">...</div> will be returned only when the Object.keys(results).length is truthy, in other words, when results has more than 0 keys. Check this article reactjs.org/docs/conditional-rendering.html

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.