result.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var castPath = require('./_castPath'),
  2. isFunction = require('./isFunction'),
  3. isKey = require('./_isKey'),
  4. toKey = require('./_toKey');
  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 = isKey(path, object) ? [path] : castPath(path);
  36. var index = -1,
  37. length = path.length;
  38. // Ensure the loop is entered when path is empty.
  39. if (!length) {
  40. object = undefined;
  41. length = 1;
  42. }
  43. while (++index < length) {
  44. var value = object == null ? undefined : object[toKey(path[index])];
  45. if (value === undefined) {
  46. index = length;
  47. value = defaultValue;
  48. }
  49. object = isFunction(value) ? value.call(object) : value;
  50. }
  51. return object;
  52. }
  53. module.exports = result;