Reputation: 93
I have a JSON which comes back like this from a API call:
"free_seat_blocks": {
"blocks_by_row": {
"22": [
[
"2218"
]
],
"23": [
[
"2315",
"2316",
"2317",
"2318"
]
],
"24": [
[
"2411",
"2412",
"2413",
"2414",
"2415",
"2416",
"2417",
"2418"
]
]
},
}
How can I access the name of the array (i.e 22, 23, etc) in ReactJs
. I need to use the name of the array to display the seat Row in table format.
Update:
I want to get the values of the keys also and display them like below -
Row Seat Number
22 2218
23 2315,2316,2317,2318
24 2411,2412,2413,2415,2416,2417,2418
Upvotes: 1
Views: 51
Reputation: 104459
blocks_by_row
is an object
and you want to access the key names. There are multiple ways of doing the same.
If you just want to display the name (keys) of blocks_by_keys
object, use Object.keys on it, it will return an array of all the key names.
Like this:
let data = {
"free_seat_blocks": {
"blocks_by_row": {
"22": [
[
"2218"
]
],
"23": [
[
"2315","2316","2317","2318"
]
],
"24": [
[
"2411","2412","2413","2414","2415","2416","2417","2418"
]
]
},
}
}
var App = () => {
return(
<div>
<table>
<tr>
<td>Rows</td>
<td>Seat No</td>
</tr>
{
Object.entries(data.free_seat_blocks.blocks_by_row).map(([row, seats]) => <tr key={row}>
<td>{row}</td>
<td>{seats.join(',')}</td>
</tr>)
}
</table>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
Upvotes: 1
Reputation: 16451
You can use Object.keys()
to get the key names of the blocks_by_row
object.
const keys = Object.keys(free_seat_blocks.blocks_by_rows); // Will return an array ['22', '23', '24'];
Upvotes: 2