I have nested array object and need to display as table format using react.
I tried below code and got stuck how to display as such
var countdetails = [
{
enabled: { IN: 354, MY: 181 },
pending: { IN: 34, MY: 11 },
total: { IN: 388, MY: 192 }
}
];
export default function App() {
return (
<div className="App">
<table>
{countdetails.map((e) => (
<>
<tr>
<td>countries</td>
<td>enabled</td>
<td>pending</td>
</tr>
<tr>
<td>{Object.keys(e.enabled)}</td>
<td>{Object.values(e.enabled)}</td>
<td>{Object.values(e.pending)}</td>
</tr>
</>
))}
</table>
</div>
);
}
Expected Output
countries enabled pending
IN 354 34
MY 181 11
5
Answers
Your data is hard to map due to its irregularity structure.
If you really want to map that data
Here you go
Hope this helps.
The UI is driven by data. Convert to a data structure more suitable for tables.
Output:
codesandbox
Here is the code to achieve your output:
Link: https://codesandbox.io/s/stackoverflow-solution-jgz6nw
Full code:
This code output will looks like your expected output.
Screenshot of output:
In my opinion it is better to just spell it out in this case. Instead of using fancy Object methods.
Either this or convert to data structure more suitable for tables as described here earlier.
As mentioned in Lin Du’s answer, it is advised to transform your data more suitable to render table data for UI.
In case you don’t have control over data and it is from external source, then you can transform your data as below
Now use this transformed data to build your table