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