Reputation: 411
Below is the object:
[
{
"Sno": "1",
"First Name": "name",
"Last Name": "las2t name",
"Email": "[email protected]",
"Amount": "2000"
},
{
"Sno": "2",
"First Name": "first name",
"Last Name": "last name",
"Email": "[email protected]",
"Amount": "2000"
}
]
Here is my code to render it in the table format
{Object.entries(schedule).map(([key,value]) => {
return(
<Table>
<thead style={{ background: '#8b8498' }}>
<tr>
<th>{key}</th>
</tr>
</thead>
<tbody>
<tr>
<td>{key[value]}</td>
</tr>
</tbody>
</Table>
)
})}
How to render the array with key value pairs dynamically ???
Upvotes: 1
Views: 690
Reputation: 7905
Object.entries(schedule).map(([key,value])...
is, admittedly, an unorthodox way of iterating through a basic array of objects, but since that's how you started it and did not ask for a different approach, here is how I would render your table:
<table>
<thead style={{ background: "#8b8498" }}>
<tr>
{Object.keys(schedule[0]).map((j, i) => (
<td key={i}>{j}</td>
))}
</tr>
</thead>
<tbody>
{Object.entries(schedule).map(([key, value]) => {
return (
<tr>
{Object.values(value).map((j, i) => (
<td key={i}>{j}</td>
))}
</tr>
);
})}
</tbody>
</table>
Sandbox: https://codesandbox.io/s/mystifying-pine-nhj4o?file=/src/App.js
Upvotes: 2
Reputation: 1191
In a case like this, assuming that every object in the array has the same keys, where schedule is the array from your exmaple:
const headKeys = Object.keys(schedule[0]);
return (
<Table>
<thead style={{ background: '#8b8498' }}>
<tr>
{headKeys.map((key, index) => {
return <th key={index}>{key}</th>;
})}
</tr>
</thead>
<tbody>
{schedule.map((item, index) => {
return (
<tr>
{headKeys.map((key, index) => {
return <td key={index}>{item[key]}</td>;
})}
</tr>
);
})}
<tr>
<td>{item[value]}</td>
</tr>
</tbody>
</Table>
);
Upvotes: 0
Reputation: 1883
You can render the headers separately and render each item in a row with the help of map.
const myArray = [
{
"Sno": "1",
"First Name": "name",
"Last Name": "las2t name",
"Email": "[email protected]",
"Amount": "2000"
},
{
"Sno": "2",
"First Name": "first name",
"Last Name": "last name",
"Email": "[email protected]",
"Amount": "2000"
}
]
const headers = Object.keys(myArray[0]);
return (
<Table>
<thead style={{ background: '#8b8498' }}>
<tr>
{headers.map((key) => (
<th>{key}</th>
))}
</tr>
</thead>
<tbody>
{myArray.map((item) => {
<tr>
<td>{item['Sno']}</td>
<td>{item['First Name']}</td>
<td>{item['Last Name']}</td>
<td>{item['Email']}</td>
<td>{item['Amount']}</td>
</tr>
})}
</tbody>
</Table>
)
other way to render using key.
const headers = Object.keys(myArray[0]);
return (
<Table>
<thead style={{ background: '#8b8498' }}>
<tr>
{headers.map((key) => (
<th>{key}</th>
))}
</tr>
</thead>
<tbody>
{myArray.map((item) => {
<tr>
{headers.map((key) => (
<td>{item[key]}</td>
))}
</tr>
})}
</tbody>
</Table>
)
Upvotes: 0