Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

result.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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;