getByPath.js.flow 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule getByPath
  8. * @flow
  9. * @typechecks
  10. */
  11. 'use strict';
  12. /**
  13. * Get a value from an object based on the given path
  14. *
  15. * Usage example:
  16. *
  17. * var obj = {
  18. * a : {
  19. * b : 123
  20. * }
  21. * };
  22. *
  23. * var result = getByPath(obj, ['a', 'b']); // 123
  24. *
  25. * You may also specify the path using an object with a path field
  26. *
  27. * var result = getByPath(obj, {path: ['a', 'b']}); // 123
  28. *
  29. * If the path doesn't exist undefined will be returned
  30. *
  31. * var result = getByPath(obj, ['x', 'y', 'z']); // undefined
  32. */
  33. function getByPath(root
  34. /*?Object | Error*/
  35. : any, path: Array<string>, fallbackValue?: any): any {
  36. let current = root;
  37. for (let i = 0; i < path.length; i++) {
  38. const segment = path[i]; // Use 'in' to check entire prototype chain since immutable js records
  39. // use prototypes
  40. if (current && segment in current) {
  41. current = current[segment];
  42. } else {
  43. return fallbackValue;
  44. }
  45. }
  46. return current;
  47. }
  48. module.exports = getByPath;