1

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;
4
  • 2
    Remember that in these for in loops, the item and item2 refers to the keys, not the values (my point is that item[item2] doesn't make sense). So for example, item will be "0" and "1" Commented Sep 24, 2014 at 22:10
  • 1
    FWIW: I would probably change the data to use arrays for both levels. Commented Sep 24, 2014 at 22:11
  • 1
    @osiris355, were you able to resolve the issue? Commented Sep 25, 2014 at 9:19
  • Yes and sorry for the late response. Thank you Commented Oct 16, 2014 at 4:14

1 Answer 1

1

@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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.