1

I have a JavaScript like this:

var metFital = { "IMP_TRAV_SP": { type: "cont", Est: 0.055 },....}
var IMP_TRAV_SP= 20;

var EvalueFital=0
  for (var par in metFital) {
     if (metFital[par].type == "cont") {
            EvalueFital = EvalueFital + ((metFital[par].Est) *par);
        }
};

I want to loop through the object "metFital", to get the "Est". Then calculate "Est"*par.

For instance when par="IMP_TRAV_SP"(first iteration of the loop), then I can get the value of Est*IMP_TRAV_SP. How should I write the stuff under the if statement?

DIY-DS
  • 243
  • 4
  • 16

1 Answers1

1

The eval way:

Not sure what are you doing and I hope you're aware of the bad sides of eval, but that's the only way you can turn this code into a working code:

var metFital = { "IMP_TRAV_SP": { type: "cont", Est: 0.055 }}
var IMP_TRAV_SP= 20;

var EvalueFital=0
  for (var par in metFital) {
     if (metFital[par].type == "cont") {
            EvalueFital = EvalueFital + ((metFital[par].Est) * eval(par));
        }
};

alert(EvalueFital);

The object bracket notation way:

If you don't mind me suggesting, you can do something like this by using the object bracket notation:

var metFital = { "IMP_TRAV_SP": { type: "cont", Est: 0.055 }}
var values = {IMP_TRAV_SP: 20};

var EvalueFital=0
  for (var par in metFital) {
     if (metFital[par].type == "cont") {
            EvalueFital = EvalueFital + ((metFital[par].Est) * values[par]);
        }
};

alert(EvalueFital);
Shomz
  • 37,421
  • 4
  • 57
  • 85