0

I have an object with property values designating the hours and minutes of a time in military time. I'm trying to have another property that uses a function outside the object to calculate the the time to twelve hour time and hold those values as additional properties.

I have the following code:

$(function () {
    console.log( startTime.twelveHourTime );
});

var startTime = {
    militaryTime: {
        hours: 23,
        minutes: 30
    },
    twelveHourTime: convertToTwelveHourTime (this.militaryTime)
    /* I would like this to result in
    twelveHourTime: {
        hours: 11,
        minutes: 30,
        amOrpm: 'PM'            
    }*/
};


function convertToTwelveHourTime (militaryTime) {

    var twelveHourTime = {
        hours: 0,
        minutes: 0,
        amOrpm: ''
    };

    if(militaryTime.hours > 12){
        twelveHourTime.hours = militaryTime.hours - 12;
    }else{
        twelveHourTime.hours = militaryTime.hours;
    }

    twelveHourTime.minutes = militaryTime.minutes;

    if(militaryTime.hours > 11){
        twelveHourTime.amOrpm = 'PM';
    }else{
        twelveHourTime.amOrpm = 'AM';
    }

    return twelveHourTime;
}

Running this code results in the following errors in the console:

Uncaught TypeError: Cannot read property 'hours' of undefined

referring to the line if(militaryTime.hours > 12).

and

Uncaught TypeError: Cannot read property 'twelveHourTime' of undefined

referring to the initial console.log.

Why is this occurring and how can I fix this code?

Jackmc1047
  • 391
  • 2
  • 5
  • 12
  • 2
    See http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations – haim770 Apr 20 '15 at 16:49
  • Your code would work if you declare and call the _twelveHourTime_ property as a function instead of referencing it to another function. – Sidd Apr 20 '15 at 16:55
  • @haim770 Thanks. I did search for an answer to this question by doing multiple google searches along the lines of "javascript how to use function to calculate object property value". How did you find the linked question? This would help me better search for answers in the future. – Jackmc1047 Apr 20 '15 at 16:58
  • The construct you're using is called an *Object Literal* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Object_literals), so I looked for **"Javascript self referencing object literal"**. – haim770 Apr 20 '15 at 17:00
  • @haim770 Also, should I delete any question I post that's marked as duplicate? Thanks. – Jackmc1047 Apr 20 '15 at 17:01
  • That's your call to make. If you think others *will* benefit from it somehow, then don't. – haim770 Apr 20 '15 at 17:01

0 Answers0