1 | var castPath = require('./_castPath'),
|
2 | isFunction = require('./isFunction'),
|
3 | isKey = require('./_isKey'),
|
4 | toKey = require('./_toKey');
|
5 |
|
6 | /**
|
7 | * This method is like `_.get` except that if the resolved value is a
|
8 | * function it's invoked with the `this` binding of its parent object and
|
9 | * its result is returned.
|
10 | *
|
11 | * @static
|
12 | * @since 0.1.0
|
13 | * @memberOf _
|
14 | * @category Object
|
15 | * @param {Object} object The object to query.
|
16 | * @param {Array|string} path The path of the property to resolve.
|
17 | * @param {*} [defaultValue] The value returned for `undefined` resolved values.
|
18 | * @returns {*} Returns the resolved value.
|
19 | * @example
|
20 | *
|
21 | * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
|
22 | *
|
23 | * _.result(object, 'a[0].b.c1');
|
24 | * // => 3
|
25 | *
|
26 | * _.result(object, 'a[0].b.c2');
|
27 | * // => 4
|
28 | *
|
29 | * _.result(object, 'a[0].b.c3', 'default');
|
30 | * // => 'default'
|
31 | *
|
32 | * _.result(object, 'a[0].b.c3', _.constant('default'));
|
33 | * // => 'default'
|
34 | */
|
35 | function result(object, path, defaultValue) {
|
36 | path = isKey(path, object) ? [path] : castPath(path);
|
37 |
|
38 | var index = -1,
|
39 | length = path.length;
|
40 |
|
41 | // Ensure the loop is entered when path is empty.
|
42 | if (!length) {
|
43 | object = undefined;
|
44 | length = 1;
|
45 | }
|
46 | while (++index < length) {
|
47 | var value = object == null ? undefined : object[toKey(path[index])];
|
48 | if (value === undefined) {
|
49 | index = length;
|
50 | value = defaultValue;
|
51 | }
|
52 | object = isFunction(value) ? value.call(object) : value;
|
53 | }
|
54 | return object;
|
55 | }
|
56 |
|
57 | module.exports = result;
|