result.js 1.4 KB

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