I'm writing a code in react, where in I want to display the json data in HTML table. I want this to be dynamic. i.e. irrespective of the type of json data I'm using, it should render in tabular format.
Here is my code with sample data.
const jsArray = [{"Model":"Mazda RX4","mpg":21,"cyl":6},{"Model":"Mazda RX4 Wag","mpg":21,"cyl":6},{"Model":"Datsun 710","mpg":22.8,"cyl":""},{"Model":"Hornet 4 Drive","mpg":21.4,"cyl":""},{"Model":"Hornet Sportabout","mpg":18.7,"cyl":8},{"Model":"Valiant","mpg":18.1,"cyl":6}];
{jsArray.length > 0 && (
<table>
<thead>
{jsArray.map((item, idx) =>
idx === 0 ? (
<th key={idx}>
{Object.values(item).forEach((val) => (
<td>{val}</td>
))}
</th>
) : (
<tr key={idx}>
{Object.values(item).forEach((val) => (
<td>{val}</td>
))}
</tr>
)
)}
</thead>
</table>
)}
When I run this code, nothing is getting rendered. When I replace <tr key={idx}>{Object.values(item).forEach((val)=> (<td>{val}</td>))}</tr> with null, In my output I see null printed in my front end. Please let me know where I'm going wrong.
jsArrayis a string, not an array. You can'tmapover it.JSON.parse(jsArray).map()becausejsArrayis a stinrgkey={idx}does get rid of the warning, it is not correct.keyis used to detect order change; using order index defeats the purpose.