I have a mongo collection to store "projects", each document stores a project with different calculations for each month of the year
a_jan : 10,
a_feb : 20,
a_mar : 25,
a_apr : 70
...
b_jan : 30,
b_feb : 10,
b_mar : 20,
b_apr : 70
...
c_jan : 80,
c_feb : 2,
c_mar : 20,
c_apr : 65
...
I've created a template helper to perform some maths calculations, involving fields for each month (i.e. : rtwc_jan = (a_jan + b_jan) / c_jan
).
There are a lot of different calculations, but same calculation is performed for each month.
How can I use a for
loop to accommodate the array key
coming from a "months" array?
This is my code (w/o the for loop...)
var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","des"];
var arrayLength = months.length;
for (var i = 0; i < arrayLength; i++) {
alert(months[i]);
// Need to Calculate rtcw for each month
var scope = {
a_jan : currentProject.a_jan,
b_jan : currentProject.b_jan,
c_jan : currentProject.c_jan,
};
var calculation_a = math.eval('(a_jan - b_jan) * c_jan / 35', scope);
scope.a = calculation_a;
var rtcw_jan = math.eval('max(a,15)', scope);
console.log(rtcw_jan);
}
I think you want to get the properties from your currentProject object by using the month as a key. Like this:
var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","des"];
var arrayLength = months.length;
var rtcw = {};
for (var i = 0; i < arrayLength; i++) {
alert(months[i]);
// Need to Calculate rtcw for each month
var scope = {
a : currentProject["a_" + months[i]],
b : currentProject["b_" + months[i]],
c : currentProject["c_" + months[i]],
};
var calculation_a = math.eval('(a - b) * c / 35', scope);
scope.a = calculation_a;
rtcw[months[i]] = math.eval('max(a,15)', scope);
console.log(rtcw[months[i]]);
}
Simplified:
var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","des"];
var rtcw = {};
for (var i = 0; i < months.length; i++)
{
var a = currentProject["a_" + months[i]];
var b = currentProject["b_" + months[i]];
var c = currentProject["c_" + months[i]];
rtcw[months[i]] = max((a - b) * c / 35, 15);
console.log(rtcw[months[i]]);
}