3

I m trying to print table with some JSON data, but I am not able to render empty array when I am using map method.

JSON DATA :

    [{
	"id": 6,
	"firstname": "Sharon",
	"lastname": "Jenkins",
	"specialties": []
}, {
	"id": 2,
	"firstname": "Helen",
	"lastname": "Leary",
	"specialties": [{
		"id": 1,
		"name": "radiology"
	}]
}, {
	"id": 4,
	"firstname": "Rafael",
	"lastname": "Ortega",
	"specialties": [{
		"id": 2,
		"name": "surgery"
	}]
}, {
	"id": 5,
	"firstname": "Henry",
	"lastname": "Stevens",
	"specialties": [{
		"id": 1,
		"name": "radiology"
	}]
}]

My Code :

 {this.state.vets.map(vet =><tr><td>{vet.firstname}</td>
                  {  
                                  
                  vet.specialties.map((subitem,i) => {
                       
                    return <td>{subitem.name}</td> })}<td>EDIT</td><td id={vet.firstname}><div class="funkyradio">

Now I am getting the following error enter image description here

As Sharon doesn't have a specialist, I need to print as N/A.

How can I check the specialities are empty and print N/A.

1
  • This is happening because the specialities array of your first object is empty so the second map function does not iterate over that field. Commented Feb 26, 2019 at 7:53

4 Answers 4

2

use conditional statment like this

{ this.state.vets.length > 0 
 ? this.state.vets.map(()=>Your logic)
 : <Your custom message/>
}
Sign up to request clarification or add additional context in comments.

Comments

1

try rendering always the TD tag, like:

{
  this.state.vets.map(vet =>
    <tr>
      <td>{vet.firstname}</td>
        <td>                
          {vet.specialties.map((subitem,i) => {
            return <span>{subitem.name}</span>
          })}
        </td>
        <td>EDIT</td>
        <td id={vet.firstname}>
          <div class="funkyradio">

Comments

1

<table>
        {dataJSON.map(({ id, firstname, lastname, specialties }) => {
          return (
            <tr>
              <td> {`${firstname} ${lastname}`} </td>
              <td> {specialties.map(specialty => specialty.name).join(",")} </td>
              <td> <span> EDIT </span> </td>
            </tr>
          );
        })}
</table>

Comments

0

Mainly for readability, instead of using the object property, I would create a separate function that will return the specialties, if any, otherwise N/A

Comments

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.