I have an object, having key and values. I'd like to pick the object and call the appropriate function from the key:

var requireViews = {
            "breadCrumbView": true,
            "headerView": false,
            "footerView": false

var that = this;

    _.each(requireViews, function(value, key){
                    if(value){ //if true?
                        if(_.functions(that, key)) that[key](); //checking is that function, and calling the function

Is it ok or can we minimize it further?

  • \$\begingroup\$ What else is requireViews used for? Could you add more context to your question? \$\endgroup\$ Jun 5 '14 at 6:18
  • \$\begingroup\$ from the requireViews, I am picking what are all the views has to render. I will override this object from other function to. and 'that' is this here. so I am finding whether the 'that' has that function(ex: breadCrumbView) the I am calling the same. - any more clarification required? \$\endgroup\$
    – 3gwebtrain
    Jun 5 '14 at 8:24

If you add a filterObject mixin (this is the one I usually use), it will be easy

    filterObject: function(obj, predicate, context) {
        return _.reduce(obj, function(memo, val, key) {
            if (predicate.call(context, val, key, memo)) memo[key] = val;
            return memo;
        }, {});

Now its simple and elegant :)

_.invoke(this, _.values(_.filterObject(requireViews, Boolean)));

If you like underscores you can use the ridiculous algorithm below (don't do it!)

_.invoke(this, _.map(_.filter(_.pairs(requireViews), _.partial(_.every, _, Boolean)), _.first))

To be honest, I'd skip underscore for this, and just do

for(var func in requireViews) {
  if(requireViews[func] && typeof this[func] === 'function') {

Otherwise, there are many different ways to go about it.

Here's a needlessly complex one, for instance:

var target = this;
  .filter(function (func) { return requireViews[func] })
  .each(function (func) { target[func]() });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.