-1

I am just wondering if there is a way in JavaScript where I can create a new list of functions based on all "name" values in the object.

For example, with the following object:

var object_ = [{"name": "first_function", "child": ["1a", "1b"]},
               {"name": "second_function", "child": ["2a", "2b"]},
               {"name": "third_function", "child": ["3a", "3b"]}];

I would like to create the following functions:

function first_function(){
      console.log("1a, 1b");
};

function second_function(){
      console.log("2a, 2b");
};

function third_function(){
      console.log("3a, 3b");
};

Thank you

11
  • Basically your array contains reference of the functions. Commented Nov 28, 2017 at 5:40
  • 1
    What is your use case and what higher level problem are you trying to solve? Commented Nov 28, 2017 at 5:42
  • Are you trying to pass references to functions to console.log()? Or are you trying to invoke the functions and pass the output of those functions to console.log()? Commented Nov 28, 2017 at 5:43
  • Possible duplicate of Javascript Array of Functions Commented Nov 28, 2017 at 5:44
  • Sorry for being unclear previously. I have edited the description. Commented Nov 28, 2017 at 5:54

1 Answer 1

2

If, given a list of metadata to create functions with:

var functionData = [
    { name: 'first_function', children: ['1a', '1b'] },
    { name: 'second_function', children: ['2a', '2b'] },
];

We can dynamically create a function by the name of each one's name property:

functionData.forEach(({name, children}) => {
    // create a function and put it under that name
    this[name] = () => {
        // and make sure it logs the corresponding data
        console.log(...children);
    }
})

Which, for example can then be called like so:

first_function();
// logs "1a", "1b"

Or even:

this[functionData[0].name]();
// logs "1a", "1b"

I added the functions to the this object just as an example.

This works for a non-strict-mode browser console; because an unqualified reference to a function tries to look for it on the window, which is the this context in that environment.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.