Austin
Austin

Reputation: 79

React display an Array of Objects with varying values, is there a better alternative to .map?

I am working with some data that I didn't create and some of the objects in the array have values while others don't.

I am used to using .map to display details in an array of objects, is there a way to display this varying array of objects?

For example:

 arr = [
{
"Name": "Bob",
"Age": 56,
"Gender": "Male",
"Description": "This describes bob"
},
{
"Name": "Mary",
"Age": 32
},
{
"Name": "Tony",
"Age": 27,
"Gender": "Male"
}
]

As some might have a gender or description value but not all for example.

How I am used to displaying out data for example:

arr.map(item => (
<div>
<p>Name: {item.Name}</p>
<p>Gender: {item.Gender}</p>
<p>Age: {item.Age}</p>
<p>"Description: {item.Description}</p>
</div>
)

I know if I do it this way I will get an error once it goes to map one with an .Age or .Description value.

Any thoughts or hints?

Upvotes: 1

Views: 38

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Option 1: Render an entry only if it has a value:

arr.map(({ Name, Gender, Age, Description }) => (
  <div>
    <p>Name: {Name}</p>
    {Gender && <p>Gender: {Gender}</p>}
    <p>Age: {Age}</p>
    {Description && <p>"Description: {Description}</p>}
  </div>
)

Option 2: Supply a default value:

arr.map(({ Name, Gender = 'N/A', Age, Description = 'N/A' }) => (
  <div>
    <p>Name: {Name}</p>
    <p>Gender: {Gender}</p>}
    <p>Age: {Age}</p>
    <p>"Description: {Description}</p>}
  </div>
)

Upvotes: 4

Related Questions