Search code examples
javascriptargumentslodash

Pass argumets to lodash _.result


Is there a way to pass arguments to lodash _.result, 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.


Solution

  • 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, Array.prototype.slice.call( arguments, 2 )) 
            : result;
    }
    
    // add our function to lodash
    _.mixin({ myResult: myResult})
    
    
    _.myResult(object, 'cheese');
    // "crumpets"
    
    _.myResult(object, 'stuff', true);
    // "nonsense"
    
    _.myResult(object, 'stuff');
    // "balderdash"