Reputation: 12190
data = [
{
"2017-08-09": [
"09:00",
"09:30",
"10:00",
"10:30",
"11:00",
"11:30",
"13:00",
"13:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30"
]
}
]
I'm trying to map over this array of objects and display info as follows:
Date 2017-08-09
available hours
09:00
09:30
10:00
...
I'm having trouble looping over this data structure,
https://codesandbox.io/s/qzrvlvx9nj
Upvotes: 3
Views: 4296
Reputation: 104369
Data is an array of objects, so first you need use map on it, after that to run loop on object property values, first use Object.keys or Object.entries to get the array, after that again use loop on available times array.
Write it like this:
{
data.map((el,i) => (
<div key={i}>
Available Dates:
{
Object.entries(el).map(([key, value], j) => (
<div key={j}>
{key}
Available Times:
{
value.map(t => <div key={t}> {t} </div>)
}
</div>
))
}
</div>
))
}
Check the working code : https://codesandbox.io/s/24n524ynz0
Working Snippet:
const data = [
{
"2017-08-09": [
"09:00",
"09:30",
"10:00",
"10:30",
"11:00",
"11:30",
"13:00",
"13:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30"
]
}
];
const App = () => (
<div>
<h2>JS Map</h2>
{
data.map((el,i) => (
<div key={i}>
Available Date:
{
Object.entries(el).map(([key, value], j) => (
<div>
{key}
Available Time:
{
value.map(t => <div>{t}</div>)
}
</div>
))
}
</div>
))
}
</div>
);
ReactDOM.render(<App />, document.getElementById("root"));
<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='root'/>
Upvotes: 5
Reputation: 2090
I've updated your link. I did not use lodash, just nested map()
calls. I first map through the initial array, and within each object I grab all the keys of that object. After that, I map through the keys of the object, and finally one last map()
through the times of each date.
You can refer the below code:
const data = [
{
"2017-08-09": [
"09:00",
"09:30",
"10:00",
"10:30",
"11:00",
"11:30",
"13:00",
"13:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30"
]
}
];
class App extends React.Component {
render() {
return (
<div>
<h2>JS Map</h2>
{
data.map(item => {
return Object.keys(item).map(date => {
return (
<div>
<h1>{date}</h1>
{item[date].map(time => {
return <h3>{time}</h3>
})}
</div>
)
})
})
}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>
Upvotes: 1