-1

I am using AJAX to return and display monthly rates based on user inputted form variables. Instead of repeating the variables 12 times, I would like to loop through the months.

Current functional code:

if(data.Jan)
    document.getElementById("Jan").value=data.Jan;
if(data.JanCurrentRate)
    document.getElementById("JanCurrent").innerHTML='$' + data.JanCurrentRate;
if(data.JanProposedRate)
    document.getElementById("JanProposed").innerHTML='$' + data.JanProposedRate;
if(data.JanDifference)
    document.getElementById("JanDifference").innerHTML='$' + data.JanDifference;

if(data.Feb)
    document.getElementById("Feb").value=data.Feb;
if(data.FebCurrentRate)
    document.getElementById("FebCurrent").innerHTML='$' + data.FebCurrentRate;
if(data.FebProposedRate)
    document.getElementById("FebProposed").innerHTML='$' + data.FebProposedRate;
if(data.FebDifference)
    document.getElementById("FebDifference").innerHTML='$' + data.FebDifference;

I would like to loop this like this:

var MonthArray = ["Jan14","Feb14"];
for (var i = 0; i < MonthArray.length; i++) {
    var month = MonthArray[i];
    if(data.month)
        document.getElementById(month.value=data.month);
    if(data.JanCurrentRate)
        document.getElementById(month+"Current").innerHTML='$' + data.JanCurrentRate;
    if(data.JanProposedRate)
        document.getElementById(month+"Proposed").innerHTML='$' + data.JanProposedRate;
    if(data.JanDifference)
        document.getElementById(month+"Difference").innerHTML='$' + data.JanDifference;
}

My problem is this: How do I make "data.JanCurrentRate" into "data.LOOPED_MONTHCurrentRate" for each month?

Dan Manson
  • 21
  • 4
  • http://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object – user2864740 Dec 29 '14 at 17:03
  • Once you understand the duplicate, the *separate* task is merely transforming the input ("MonXX") to the indexer ("MonZZ"). If at all possible, I would simplify the data/design to make the transformation more trivial - eg. use an array of months objects with "Current", "Proposed", "Difference" properties. – user2864740 Dec 29 '14 at 17:03
  • `data[month+"CurrentRate"]`, obviously. – Niet the Dark Absol Dec 29 '14 at 17:04

1 Answers1

0

Thanks to Niet the Dark Absol, I have solved this problem. Here is the functional loop:

var MonthArray = ["Jan","Feb"];
for (var i = 0; i < MonthArray.length; i++) 
{
    var month = MonthArray[i];
    if(data[month])
        document.getElementById(month).value=data[month];
    if(data[month+"CurrentRate"])
        document.getElementById(month+"Current").innerHTML='$' + data[month+"CurrentRate"];
    if(data[month+"ProposedRate"])
        document.getElementById(month+"Proposed").innerHTML='$' + data[month+"ProposedRate"];
    if(data[month+"Difference"])
        document.getElementById(month+"Difference").innerHTML='$' + data[month+"Difference"];
}
Dan Manson
  • 21
  • 4