0

I have an object like this:

options: {
  'Signature': "[Customer First Name] [Customer Last Name]"
  'First Name': "[Customer First Name]"
  'Last Name': "[Customer Last Name]"
}

And I need to convert it so that the values become functions that use that value like this:

options: {
  'Signature': function(){ this.insertHTML('[Customer First Name][Customer Last Name]'); }
  'First Name': function(){ this.insertHTML('[Customer First Name]'); }
  'Last Name': function(){ this.insertHTML('[Customer Last Name]'); }
}

But I'm not sure how to do this. So as an example I want to be able to do something like:

var newOptions = functionify(options);
0

2 Answers 2

2

Here's one potential solution. Iterate over the keys of options and build up a new object:

var newOptions = Object.keys(options).reduce(function ( obj, option ) {
  obj[ option ] = function () {
    this.insertHTML(options[ option ]);
  };
  return obj;
}, {});

Note that this inside those functions is unlikely to refer to what you expect it to, unless you're invoking those functions with some other explicit context (e.g. via call or apply).

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

Comments

1

In JavaScript, it's possible to create functions which return functions.

For example:

function functionify(str) {
  return function() {
    return str; // Or whatever you want in your function body.
  };
}

So, by calling functionify and passing some string to it, you'll get in return a function which returns that string:

var fun = functionify('Hello, World!'); // fun is now a function

fun(); // returns "Hello, World!"

This can be applied to keys and values of an object in any of several ways (depending on your preference; a for-in loop, Object.keys to name a couple).

Another example:

obj['key'] = functionify(obj['key']);
obj['key']();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.