kris kris - 4 years ago 301
Javascript Question

Pass argumets to lodash _.result

Is there a way to pass arguments to lodash

, for the case, when second attribute is method name? Or is there alternative method (preferable lodash) of doing this?

Usage example could be like this:

var object = {
'cheese': 'crumpets',
'stuff': function( arg1 ) {
return arg1 ? 'nonsense' : 'balderdash';

_.result(object, 'cheese');
// => 'crumpets'

_.result(object, 'stuff', true);
// => 'nonsense'

_.result(object, 'stuff');
// => 'balderdash'

Thank you.

Answer Source

I looked at the source code of lodash _.result function and there is no support for this. You can implement your own function for this and extend lodash with it using _.mixin.

function myResult(object, path, defaultValue) {
    result = object == null ? undefined : object[path];
    if (result === undefined) {
        result = defaultValue;
    return _.isFunction(result) 
        ? result.apply(object, arguments, 2 )) 
        : result;

// add our function to lodash
_.mixin({ myResult: myResult})

_.myResult(object, 'cheese');
// "crumpets"

_.myResult(object, 'stuff', true);
// "nonsense"

_.myResult(object, 'stuff');
// "balderdash"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download