0

I am using javascripts .find() function to return an object if a value exists however I get an undefined error

this.reduceoptionRadio = 'instalment'
this.calculatorResult = 
[
    {
        "newCalculatedInstallmentsNo": "50",
        "newContractEndDate": "20250701",
        "newResidual": "0",
        "newInstalment": "4071.91",
        "newTerm": "52",
        "outBalanceAvaf": null,
        "restructureType": "term"
    },
    {
        "newCalculatedInstallmentsNo": "52",
        "newContractEndDate": "20250901",
        "newResidual": "0",
        "newInstalment": "3939.93",
        "newTerm": "54",
        "outBalanceAvaf": null,
        "restructureType": "instalment"
    }
]



this.calculateFormData = this.calculatorResult.find(
  function(el) {
  return el.restructureType === this.reduceoptionRadio;
  }
);
console.log(this.calculateFormData);

How can I get the value of this.reduceoptionRadio to reflect with the find function? The value of this.reduceoptionRadio is dynamic, I just hardcoded here so I can have relevant code to explain.

Exact error in console reads ERROR TypeError: Cannot read property 'reduceoptionRadio' of undefined

skydev
  • 1,867
  • 9
  • 37
  • 71

1 Answers1

0

The ES5 syntax of a function function(el) creates a new context (a new this). Inside it, this refers to the function itself, where reduceoptionRadio is logically undefined.

An old (pre-ES6) and dirty workaround used to be :

var self = this;

this.calculateFormData = this.calculatorResult.find(
  function(el) {
      return el.restructureType === self.reduceoptionRadio;
  }
);

Instead, use the newer ES6 "fat arrow" syntax, which passes the context (this) inside the function :

this.calculateFormData = this.calculatorResult.find( el => el.restructureType === this.reduceoptionRadio );
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • when I try the ES6 version I get the `this.calculateFormData` as undefined if I console.log it `this.calculateFormData = this.calculatorResult.find( el => el.restructureType === this.reduceoptionRadio );` `console.log(this.calculateFormData);` – skydev May 25 '21 at 07:06
  • 1
    @skydev not reproducible: https://jsfiddle.net/q0j1o3nt/ . Is the array populated asynchronously? – adiga May 25 '21 at 07:11
  • @adiga yes it is populated asynchronously. It works with flat data but not asynchronously – skydev May 25 '21 at 07:14
  • 2
    @skydev you need to do `this.calculatorResult.find` after the array is populated. – adiga May 25 '21 at 07:15
  • Of course, if you try to find things in an array that's not yet populated, you won't find anything :) – Jeremy Thille May 25 '21 at 07:20