Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 785
Kris Ku Avatar asked Dec 30 '15 11:12

Kris Ku


People also ask

Is null or undefined Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.

What does Lodash get return?

get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

What is Noop Lodash?

The Lodash _. noop() method is used to return “undefined” irrespective of the arguments passed to it. Syntax: _.noop() Parameters: This method can take optional parameters of any type. Returns: This method returns undefined.

How do you check undefined in Lodash?

The _. isUndefined() method is used to find whether the given value is undefined or not. It returns True if the given value is undefined. Otherwise, it returns false.


1 Answers

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"
like image 163
Volodymyr Synytskyi Avatar answered Oct 03 '22 18:10

Volodymyr Synytskyi