1

I have a function that returns a string of a method I want to call.

For example:

I call the function and it returns the string "price". I then want to use the word price to call another method ( contractObject.price() )

Is there any way to accomplish this in Node JS?

  • Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – CherryDT Jan 28 '22 at 21:50

3 Answers3

2

Yes, you can use square brackets:

let methodName = "price";

contractObject[methodName]();

contractObject["price"] is equivalent to contractObject.price.

Caleb Denio
  • 1,465
  • 8
  • 15
2

This will work.

const functionToCall = yourFunction(); // this returns "price"
// call the price function like this
contractObject[functionToCall]();
Omkar Kulkarni
  • 1,091
  • 10
  • 22
-3

Ended up figuring out the answer. If I make the whole function a string and then use eval( ) it calls the method I wanted