getByPath.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. *
  8. * @typechecks
  9. */
  10. 'use strict';
  11. /**
  12. * Get a value from an object based on the given path
  13. *
  14. * Usage example:
  15. *
  16. * var obj = {
  17. * a : {
  18. * b : 123
  19. * }
  20. * };
  21. *
  22. * var result = getByPath(obj, ['a', 'b']); // 123
  23. *
  24. * You may also specify the path using an object with a path field
  25. *
  26. * var result = getByPath(obj, {path: ['a', 'b']}); // 123
  27. *
  28. * If the path doesn't exist undefined will be returned
  29. *
  30. * var result = getByPath(obj, ['x', 'y', 'z']); // undefined
  31. */
  32. function getByPath(root
  33. /*?Object | Error*/
  34. , path, fallbackValue) {
  35. var current = root;
  36. for (var i = 0; i < path.length; i++) {
  37. var segment = path[i]; // Use 'in' to check entire prototype chain since immutable js records
  38. // use prototypes
  39. if (current && segment in current) {
  40. current = current[segment];
  41. } else {
  42. return fallbackValue;
  43. }
  44. }
  45. return current;
  46. }
  47. module.exports = getByPath;