1

I need to call a function from an object with a string. For example:

type = 'human'

json: {
    action: 'run',
    type: this.type, //<- Here I want to call a function call 
    'Human', or whatever value has the variable type.
}

Basically I want to parse the string and call the function that matches the string.

This is for angular. I'm trying to use window['function'] name but it angular says its not a function.

Thank you!

Blinhawk
  • 379
  • 2
  • 7
  • 19
  • To turn a string into code, you're probably looking at using [eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval), **however** this is generally a bad idea (and a security nightmare) and is often a sign your doing something wrong. Could you just could pass an identifier and then use that to select which function to run instead? – DBS Nov 06 '19 at 17:26
  • Does this answer your question? [Calling a JavaScript function named in a variable](https://stackoverflow.com/questions/1723287/calling-a-javascript-function-named-in-a-variable) – GrafiCode Nov 06 '19 at 17:28
  • if I use window['functionName'] angular/typescript says the function does not exists. The name of the variable is coming from a http request. – Blinhawk Nov 06 '19 at 17:36

2 Answers2

0

So, what I'm guessing you mean is that you have an object with a property, and the value of that property is ALSO the name of the function you want to call.

For example, maybe you have an array of objects:

const obs = [{func:'x',val:2}, {func:'y',val:3}];

And you want to iterate over those objects and, for the first one, call a function 'x' and for the second one, call a function 'y'.

One way to do that is to have your functions as part of an object

const functions = {
  x: function(val) {
    console.log('inside function x');
    console.log(val);
  },
  y: function(val) {
    console.log('inside function y');
    console.log(val);
  }
}

Then, you can do something like this

obs.forEach(object => functions[object.func](object.val));
TKoL
  • 13,158
  • 3
  • 39
  • 73
0

Usually we parse the key to call a matched function

haibodong
  • 11
  • 4