javascriptnode.jsecmascript-6code-generationdynamic-code

Dynamically create a method from a string in ES6 javascript (non browser)


In javascript code, I have a string that defines a property path within an object. For instance

var def = "contact.email"

How can I get the following function from this string?

o => o.contact.email

So that I can use it in the following way:

var person = {
    name: 'Test',
    contact: { email: 'test@test.test' }
}

var emailGetter = MagicCompileFunction('contact.email');

var email = emailGetter(person);
// here, email should hold the value of person.contact.email

The path string is unknown at compile time. It could be provided by the user as well.

The solution should work in non-browser environments too (where there is no window object), for instance in NodeJS server side javascript.

I know that one solution would be to create a generic method that takes an object and a string as arguments (valueGetter(person, "contact.email") for instance), where the string defines the path within the object, and then split the string on each dot '.' and follow the path on the object. But I don't want this algorithm to execute in every call to getter function. I need a dynamically compiled method that would give me a final getter that would access the desired (sub)property immediately.


Solution

  • You can achieve this using Function constructor

    var person = {
        name: 'Test',
        contact: { email: 'test@test.test' }
    }
    var maginFunction = (def) => new Function('o','return o.'+ def);
    
    var emailGetter = maginFunction('contact.email');
    
    var email = emailGetter(person);
    console.log(email);