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.
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.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With