I have written three for loops for displaying data on the screen using JavaScript. How can I simplify the following code?
My Json Format:
{
"result": {
"type": "SUCCESS",
"data": [{
"monthName": "July",
"monthId": 7,
"weeks": [{
"days": [{
"day": "Sunday",
"date": "07/31/2016"
}],
}],
}],
}
}
var monthObj = response.result.data;
for (var i = 0; i < monthObj.length; i++) {
for (var t = 0; t < monthObj[i].weeks.length; t++) {
for (var s = 0; s < monthObj[i].weeks[t].days.length; s++) {
}
}
}
This is my loop, here I have written 3 loops.
Is there any easy way to simplify these loops?
asked Dec 29, 2016 at 11:56
sathish kumar
9362 gold badges23 silver badges60 bronze badges
1 Answer 1
It depends how your data looks like and what you want to do inside the loop. If you expect to have more than one entry for month, week and day and you want to perform some action on all of them, you will need three loops.
I'd recommend using forEach instead of for though:
const data = {
"result": {
"type": "SUCCESS",
"data": [{
"monthName": "July",
"monthId": 7,
"weeks": [{
"days": [{
"day": "Sunday",
"date": "07/31/2016"
}],
}],
}],
}
}
data.result.data.forEach(month => {
month.weeks.forEach(week => {
week.days.forEach(day => console.log(day))
})
})
answered Dec 29, 2016 at 12:04
Christian Zosel
1,4241 gold badge9 silver badges16 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
"data" : ["07/31/2016"], which can give you all the other info when converted to a Date object. It would reduce everything down to one loop. (depending on what you're doing with those dates...)