AnotherMike AnotherMike - 2 months ago 11
Javascript Question

If Statement that Tests Multiple Ternary Operators Javascript

I'm wondering why my solution doesn't work. I have the following:

//tells if type should be included in the row data
isInReport = {factual: true, eac: false, variance: false}

//report has hundreds of objects, each with a type of either Plan, Factual, EAC, Variance
report = [{type: "Plan"}, {type: "Factual"}, {type: "EAC"}, {type: "Variance"}];


I need to loop through the report array, and do something always if item.type is "Plan," or if it is one of the other 3 types, but only if it is true in the isInReport object. So in my example the if statement should pass if item.type is "Plan," or "Factual"

Why doesn't this code work? The logic seems right to me even if a little odd. When I've tested it always returns all types no matter what. Thanks for any help!

report.map(function (item) {
if (
item.type === "Plan" ||
item.type === (isInReport.factual) ? "Factual" : "Plan" ||
item.type === (isInReport.eac) ? "EAC" : "Plan" ||
item.type === (isInReport.variance) ? "Variance" : "Plan"
) {
//do stuff
}
});

Answer

Did you want to do:

if ( item.type === "Plan" || isInReport[ item.type.toLowerCase() ] ) {
    //do stuff
}

There is a comment suggesting this is not correct. Can you confirm what you expect as a result for the 4 items in report?

//tells if type should be included in the row data
isInReport = {factual: true, eac: false, variance: false}

//report has hundreds of objects, each with a type of either Plan, Factual, EAC, Variance
report = [{type: "Plan"}, {type: "Factual"}, {type: "EAC"}, {type: "Variance"}];

report.forEach(function(item){
  if ( item.type === "Plan" || isInReport[ item.type.toLowerCase() ] ) {
    console.log("Item Type:" + item.type + " PASSED TEST");
  } else {
    console.log("Item Type:" + item.type + " FAILED TEST");
  }
});

If you wanted to stick with the way you started with then you want to use some brackets to better control the order or opperations.

//tells if type should be included in the row data
isInReport = {factual: true, eac: false, variance: false}

//report has hundreds of objects, each with a type of either Plan, Factual, EAC, Variance
report = [{type: "Plan"}, {type: "Factual"}, {type: "EAC"}, {type: "Variance"}];

report.forEach(function(item){
  if (
    item.type === "Plan" ||
    item.type === (isInReport.factual ? "Factual" : "Plan") ||
    item.type === (isInReport.eac ? "EAC" : "Plan") ||
    item.type === (isInReport.variance ? "Variance" : "Plan")
  ) {
    console.log("Item Type:" + item.type + " PASSED TEST");
  } else {
    console.log("Item Type:" + item.type + " FAILED TEST");
  }  
});

Comments