Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use a function argument as an object key value

I have an object:

let commands = {
  help: () => consoleDialog('defaultMessage'),
  ls: () => consoleDialog('defaultMessage2')
};

How can I use an argument as a key identifier to invoke the function held in value:

function changeText(currentValue) {
  commands.currentValue()
}

In the example above, if currentValue is equal to help, then commands.help() should be executed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use it like..

let commands = {
  help: () => console.log("defaultMessage"),
  ls: () => console.log("defaultMessage2")
};

function changeText(currentValue) {
  // takes the property of the object dynamically
  commands[currentValue]();
}

changeText("help");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading