Reputation: 5566
I am trying to check the week object's minutes and hours and I cannot figure out what I am doing wrong. The week object can contain variations of Day1 - Day7 so I dont want to check them specifically. I want to check the nested Hours/Minutes. I also don't want to use jquery and it has to work with ie8. Any help would be greatly appreciated.
week = {
Day1: {
Hours: 6,
Minutes: 20
},
Day2: {
Minutes: 45
},
Day3: {
Hours: 8,
Minutes: 15
}
};
hoursInValid = false;
minutesInValid = false;
for (var item in week) {
if (week.hasOwnProperty(item)) {
for (var i = 0; i < week[item].length; i++ )
{
if (week[item][i].Hours > 6) {
hoursInValid = true;
break;
}
if (week[item][i].Minutes > 20) {
minutesInValid = true;
break;
}
}
}
}
Upvotes: 1
Views: 46
Reputation: 10627
Do this instead:
var invalidHours = {}, invalidMinutes = {};
for(var i in week){
var w = week[i];
if(w.hasOwnProperty('Hours')){
invalidHours[i] = w.Hours > 6 ? true : false;
}
else{
// no hours
}
if(w.hasOwnProperty('Minutes')){
invalidMinutes[i] = w.Minutes > 20 ? true : false;
}
else{
// no minutes
}
}
if(invalidHours.Day1) // day 1 hours are invalid
if(invalidMinutes.Day2) // day 2 minutes are invalid
Upvotes: 1
Reputation: 81
Try this:
for (var day in week) {
for (var unit in week[day]) {
if (unit === 'Hours' && week[day][unit] > 6) {
hoursInvalid = true;
} else if (unit === 'Minutes' && week[day][unit] > 20) {
minutesInvalid = true;
}
}
}
The break statements may not allow you to iterate over all the properties.
Upvotes: 1
Reputation: 3642
I don't see the need for the internal for
loop. This is the solution I came up with. I added checks to make sure the DayN
objects have Hours
and Minutes
properties.
week = {
Day1: {
Hours: 6,
Minutes: 20
},
Day2: {
Minutes: 45
},
Day3: {
Hours: 8,
Minutes: 15
}
};
hoursInValid = false;
minutesInValid = false;
for (var item in week) {
if (week[item].hasOwnProperty('Hours')) {
if (week[item].Hours > 6) {
hoursInValid = true;
break;
}
}
if (week[item].hasOwnProperty('Minutes')) {
if (week[item].Minutes > 20) {
minutesInValid = true;
break;
}
}
}
Upvotes: 1