# Is there a simple way to use Underscorejs to achieve this?

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 = {
"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?

• What else is requireViews used for? Could you add more context to your question? – 200_success Jun 5 '14 at 6:18
• 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? – 3gwebtrain Jun 5 '14 at 8:24

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

_.mixin({
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') {
this[func]();
}
}


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

Here's a needlessly complex one, for instance:

var target = this;
_.chain(requireViews)
.keys()
.filter(function (func) { return requireViews[func] })
.intersection(_.functions(this))
.each(function (func) { target[func]() });