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"
}]
}]
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
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.
Share Improve this question edited Feb 26, 2019 at 10:26 Egon Allison 1,3961 gold badge14 silver badges22 bronze badges asked Feb 26, 2019 at 7:45 Srikanthreddy KothaSrikanthreddy Kotha 552 silver badges4 bronze badges 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. – Atin Singh Commented Feb 26, 2019 at 7:53
4 Answers
Reset to default 2use conditional statment like this
{ this.state.vets.length > 0
? this.state.vets.map(()=>Your logic)
: <Your custom message/>
}
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">
<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>
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745310974a4621996.html
评论列表(0条)