Reputation: 5566
I am having issues figuring out how to find the nulls in my object and replace them with 0's. I was able to access the correct member at one point but once it left the loop their were no longer assigned the 0. I am fairly new to working with objects in js so I am pretty lost. Any help would be greatly appreciated.
var data = {
0 : {
Day1: {
Hours: 6,
Minutes: null
},
Day2: {
Minutes: 45
},
Day3: {
Hours: 8,
Minutes: 15
},
1 : {
Day1: {
Hours: 6,
Minutes: 20
},
Day2: {
Hours: 45
Minutes: null
},
Day3: {
Hours: 8,
Minutes: 15
}
};
for (var item in data) {
for (var item2 in item) {
item[item2].Hours = item[item2].Hours || 0;
item[item2].Minutes = item[item2].Minutes || 0;
}
}
//Ignore this line. Just assigning onject to angular scope when finished
$scope.timeInfo = data;
Upvotes: 1
Views: 56
Reputation: 3642
@Ian is correct when he says that in for (variable in object)
loops variables refers to the object key property names. So in your case, one way to achieve your objective is the following:
(NOTE: I went ahead and added some missing braces in your data
object.)
var data = {
0 : {
Day1: {
Hours: 6,
Minutes: null
},
Day2: {
Minutes: 45
},
Day3: {
Hours: 8,
Minutes: 15
}
},
1 : {
Day1: {
Hours: 6,
Minutes: 20
},
Day2: {
Hours: 45,
Minutes: null
},
Day3: {
Hours: 8,
Minutes: 15
}
}
};
for (var item in data) {
for (var item2 in data[item]) {
data[item][item2].Hours = data[item][item2].Hours || 0;
data[item][item2].Minutes = data[item][item2].Minutes || 0;
}
}
Upvotes: 1