So Im trying to render in jsx a list of 7 days with open hours, taking data from my json file. I want to make it looks somehow like this:
Mon 09:00 – 21:00
Tue 09:00 – 21:00
Wed 09:00 – 21:00
Thu 09:00 – 21:00
Fri 09:00 – 21:00
Sat 11:00 – 21:00
Sun 11:00 – 21:00
In my json file it looks like this:
JavaScript
x
5
1
openHours: [
2
{ days: [1, 2, 3, 4, 5], from: '09:00', to: '21:00' },
3
{ days: [6, 0], from: '11:00', to: '21:00' },
4
],
5
So i tried to map openHours, got 2 objects, but when I try to map those 2 objects I get error that map is not a function. I wanted it to map in this way, that in this case, it returns 5 items with 09:00-21:00 and 2 items 11:00-21:00, but there can be case, that openHours will containt 3 objects, like days 1-5, day 6 and day 0. Is there any way to do it?
Advertisement
Answer
You should be able to iterate over openHours
and then, within that loop, iterate over days
.
JavaScript
1
19
19
1
function App() {
2
const DAY_LOOKUP = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
3
4
const openHours = [
5
{ days: [1, 2, 3, 4, 5], from: '09:00', to: '21:00' },
6
{ days: [6, 0], from: '11:00', to: '21:00' },
7
]
8
9
return openHours.map(group => {
10
return group.days.map(day => (
11
<p key={day}>{DAY_LOOKUP[day]} {group.from} - {group.to}</p>
12
))
13
})
14
}
15
16
ReactDOM.render(
17
<App />,
18
document.getElementById("react")
19
);
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
3
<div id="react"></div>