Change method in a statement conditionally

Is possible to change a method according to the input without the need to duplicate a function? For example, if the variable intent assumes the value payment, the method applied to the object stripe is paymentIntents. If intent is setup, then the method applied to the object stripe is setupIntent

let intent = req.userIntent


What I wouldn’t like to do is:

let intent = req.userIntent

if (intent = "payment") {
   } else if (intent = "setup") {  

Clarifying, the code is way bigger, but the same for both situations, except by the method (paymentIntents or setupIntent), and I don’t want to repeat the code.


You can use the conditional operator in combination with bracket notation:

const prop = intent === 'payment'
  ? 'paymentIntents'
  : intent === 'setup'
    ? 'setupIntents'
    : null;

or, you may be able to do

stripe[intent + 'intents']?.update("teste");

Note that = is assignment, not comparison. You want === to compare, not =.

If the intent can be only 'payment' or 'setup', it’s easier:

stripe[intent === 'payment' ? 'paymentIntents' : 'setupIntents'].update("teste");


stripe[intent + 'intents'].update("teste");