I think I have pretty easy question, but can't figure it out by my own. I am trying to map json object into table in react. Each key represent a column, and each value in the array is a row. How should I map it to achieve table structure like example below?
Json structure:
{
"code": [
"111111",
"222222",
"333333"
],
"name": [
"nameA",
"nameB",
"nameB"
],
"price": [
1,
2,
3,
]
}
Structure of the table should be like:
| code | name | price |
|---|---|---|
| 111111 | nameA | 1 |
| 222222 | nameB | 2 |
| 333333 | nameC | 3 |
Something like this would work with your structure of js object or json . The problem is your structure should be changed to make it easier to iterate through.
class Table extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
var abc={
"code": [
"111111",
"222222",
"333333"
],
"name": [
"nameA",
"nameB",
"nameB"
],
"price": [
1,
2,
3,
]
}
var trArr=[]
var tb=function(){
abc.code.map(function(v,i){
trArr.push(
<tr key={i}>
<td>{abc.code[i]}</td>
<td>{abc.name[i]}</td>
<td>{abc.price[i]}</td>
</tr>
)
})
return(
<table>
<thead>
<tr><th>code</th><th>name</th><th>price</th></tr>
</thead>
<tbody>
{trArr}
</tbody>
</table>
)
}()
return (
<div>
{tb}
</div>
)
}
}
Your structure should look more like this, so you can iterate/map over it as individual container records and not split up columns/values in separate arrays
[{
"code": "11111",
"name": "nameA",
"price": 1
},
{
"code": "22222",
"name": "nameB",
"price": 2
},
{
"code": "33333",
"name": "nameC",
"price": 3
}
]