How to name a function based on a string?

Is there a way to name a function base on a string?

Scenario:

I need to create an array of funcs. For this I'm looping through an array of objects, and the idea would be to name the function based on the object.name.

Ideally for objects named a and b, funcs would have [func1_a, func2_a, func1_b, func2_b]

Example:

let types = [
  {
    'name': 'a',
    'key': 'a_key',
    'value': 'this is a value',
  },
  {
    'name': 'b',
    'key': 'b_key',
    'value': 'this is b value',
  }
];
let funcs = [];
for (const type in types) {
  test.push(
    function func1_{type.name} {
      // do something with type.key and type.value
    },
    function func2_{type.name} {
      // do something with type.key and type.value
    }
 )
}

Problem

I know function func1_{type.name} is not correct, thus I'm trying to find the way to do this. Any ideas? Or something like this is even possible?

Note: most of the resources I found are how to call a function based on a string, but nothing on how to name/create a function based on a string.

Thanks in advance!

5 answers

  • answered 2021-05-13 22:28 R.LM

    a good way would be to use dicts instead :

    
    let types = [
      {
        'name': 'a',
        'key': 'a_key',
        'value': 'this is a value',
      },
      {
        'name': 'b',
        'key': 'b_key',
        'value': 'this is b value',
      }
    ];
    let funcs = [];
    const test = {}
    types.forEach(({name, key, value}, index) => test[`func${index}_name`] = () => {
        // anything you want 
    })
    

  • answered 2021-05-13 22:33 imvain2

    Instead of an array use an object and you can create functions and call them later on.

    let types = [{
        'name': 'a',
        'key': 'a_key',
        'value': 'this is a value',
      },
      {
        'name': 'b',
        'key': 'b_key',
        'value': 'this is b value',
      }
    ];
    let funcs = {};
    
    for (const type in types) {
      funcs["func1_" + types[type].name] = function(params) {
        console.log(params);
      }
      
      funcs["func2_" + types[type].name] = function(params) {
        console.log(params);
      }
    }
    
    funcs["func1_a"]("test");
    funcs["func2_a"]("test2");

  • answered 2021-05-13 22:36 digitalniweb

    You can have object of functions and call those like this...

    let functions = {
      func1: function(string){
        console.log(string)
      }
    }
    let callFunctionString = "func1"
    functions[callFunctionString]("hello world")
    

  • answered 2021-05-13 23:03 Redouane

    The eval() function evaluates JavaScript code represented as a string.

    let types = [
        {
            'name': 'a',
            'key': 'a_key',
            'value': 'this is a value',
        },
        {
            'name': 'b',
            'key': 'b_key',
            'value': 'this is b value',
        }
    ];
    // generate function
    for (let inc in types) {
        let code = 'function ' + types[inc]['name'] + '(' + types[inc]['key'] + ') {console.log( "hello "+' + types[inc]['key'] + '+" !");}';
        eval(code);
    }
    // call function
    for (let inc in types) {
        let code = types[inc]['name'] + '("' + types[inc]['value'] + '")';
        eval(code);
    }
    

  • answered 2021-05-14 00:49 Glorified

        let types = [
          {
            //0 : 'abc',
            'name': 'a',
            'key': 'a_key',
            'value': 'this is a value',
          },
          {
            'name': 'b',
            'key': 'b_key',
            'value': 'this is b value',
          }
        ];
        
        funcs = [];
        for(const i in types){
            let j = window["funcs"+i+"_"+types[i].name] = () => { console.log(types[i].value) }
            funcs.push(j);
        }
        console.log(funcs);
        funcs0_a(); funcs1_b();

    If you want to check whether they are added in the window:

    var f = Object.keys(window).filter(function(x){
        if (!(window[x] instanceof Function)) return false;
        return !/\[native code\]/.test(window[x].toString()) ? true : false;
    });
    
    console.log(f);