Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var baseGet = require('../internal/baseGet'),
2
baseSlice = require('../internal/baseSlice'),
3
isFunction = require('../lang/isFunction'),
4
isKey = require('../internal/isKey'),
5
last = require('../array/last'),
6
toPath = require('../internal/toPath');
7
8
/**
9
* This method is like `_.get` except that if the resolved value is a function
10
* it is invoked with the `this` binding of its parent object and its result
11
* is returned.
12
*
13
* @static
14
* @memberOf _
15
* @category Object
16
* @param {Object} object The object to query.
17
* @param {Array|string} path The path of the property to resolve.
18
* @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
19
* @returns {*} Returns the resolved value.
20
* @example
21
*
22
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
23
*
24
* _.result(object, 'a[0].b.c1');
25
* // => 3
26
*
27
* _.result(object, 'a[0].b.c2');
28
* // => 4
29
*
30
* _.result(object, 'a.b.c', 'default');
31
* // => 'default'
32
*
33
* _.result(object, 'a.b.c', _.constant('default'));
34
* // => 'default'
35
*/
36
function result(object, path, defaultValue) {
37
var result = object == null ? undefined : object[path];
38
if (result === undefined) {
39
if (object != null && !isKey(path, object)) {
40
path = toPath(path);
41
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
42
result = object == null ? undefined : object[last(path)];
43
}
44
result = result === undefined ? defaultValue : result;
45
}
46
return isFunction(result) ? result.call(object) : result;
47
}
48
49
module.exports = result;
50
51