0

I have an object like this:

let column = ["A", "B", "C", "D"]

validation: {
    type: ...
    id: ...
    // and possible report that could exists or not
    reportA: ...
    reportB: ...
    //other possible reports added
}

I have a column of 4 label, and I have to check if in the validation object exists the report created for the column.

So I should check if validation.report"column" exists, if it exists I save the value of the report["column"] in the state, also I'll do a call function.

How Can I check if column has the corresponding report in the validation object?

I have tried something like this:

  column.forEach( value => {
        if(this.state.validation + `report${value}`){
         setState(....)
     }
   else{
    this.getData(value)
    }

it always print me as the data exists inside this.state.validation

Jack23
  • 1,368
  • 7
  • 32

1 Answers1

1

You can access a property of an object with square brackets.

const column = ["A", "B", "C", "D"];

const state = {
  validation: {
    reportA: {},
    reportB: {},
  }
}

column.forEach((value) => {
  if(state.validation[`report${value}`] != null) {
    console.log(value); // prints A and B
  }
});

What you did in your if clause was a truthy check on '[object Object]reportA' (A through D) and that is always true. The + Operator treats it as a String.

Shumuu
  • 122
  • 15