javascriptarraysstringfunctionnamed

How do I create a exported named function from a array of strings in a for loop?


Suppose I have made a function that I use to extract data. This function would extract data from a json object.

This json object has the following type of structure:

[
   "variable_name1",
   "value1",
   "value2",
   "value3",
],
[
   "variable_name2",
   "value1",
   "value2",
   "value3",
]

And so forth...

I want to create a function like this:

export const myFunctionName1 = () => {
    return extractData(jsonObject[0]);
}

export const myFunctionName2 = () => {
    return extractData(jsonObject[1]);
}

Etcetera...

However, I want to simplify this into a for loop so that I can dynamically create the functions based on a name that I specify.

So for example:

const variableNames = [
    "myFunctionName1",
    "myFunctionName2",
]

This variableNames Array, should be used to create functions based on the index.

So ideally I would do something like:

for (const [index, name] of variableNames.entries()) {
    eval(`export const ${name} = () => {
        return extractData(jsonObject[${index + 1}]);
    }`);
}

EDIT (that should actually be an Array...):

variableNames.forEach((name, index) => {
eval(`export const ${name} = () => {
        return extractData(jsonObject[${index + 1}]);
    }`);
});

This however, does not work.

I would also like to refrain from using eval, and would like to elsewhere be able to call: myFunctionName1() in a different script that imports it.

Is this possible? And if so, how would this be accomplished? It seems like a trivial task, but I'm having a hard time.

EDIT: I think I should just try and convert the JSON object structure into a different structure and use that instead of doing this wizardry.

EDIT: I could do something like this:

const myFunctions = [
   const myFunctionName1 = () => { return extractData(jsonObject[0]); },
   const myFunctionName2 = () => { return extractData(jsonObject[1]); }
]

Etcetera, but I don't think it is very elegant. Ideally I would just map the variable_name to a function name and export that somehow.


Solution

  • You can always create an object and dynamically add the functions to it.

    Then simply call them like:

    callBacks.functionName()

    function extractData(obj){
      return  obj
    }
    let jsonObject = [[
       "variable_name1",
       "value1",
       "value2",
       "value3",
    ],
    [
       "variable_name2",
       "value1",
       "value2",
       "value3",
    ]];
    
    let callBacks = {};
    
    const variableNames = [
        "myFunctionName1",
        "myFunctionName2",
    ]
    
    variableNames.forEach((f,index) => {
        callBacks[f] = () => {return extractData(jsonObject[index]);}
    });
    
    console.log(callBacks.myFunctionName1())
    console.log(callBacks.myFunctionName2())