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:
openHours: [ { days: [1, 2, 3, 4, 5], from: '09:00', to: '21:00' }, { days: [6, 0], from: '11:00', to: '21:00' }, ],
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
.
function App() { const DAY_LOOKUP = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const openHours = [ { days: [1, 2, 3, 4, 5], from: '09:00', to: '21:00' }, { days: [6, 0], from: '11:00', to: '21:00' }, ] return openHours.map(group => { return group.days.map(day => ( <p key={day}>{DAY_LOOKUP[day]} {group.from} - {group.to}</p> )) }) } ReactDOM.render( <App />, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="react"></div>