getPropertyByPath.js 775 B

1234567891011121314151617181920212223
  1. //
  2. 'use strict';
  3. // Resolves property names or property paths defined with period-delimited
  4. // strings or arrays of strings. Property names that are found on the source
  5. // object are used directly (even if they include a period).
  6. // Nested property names that include periods, within a path, are only
  7. // understood in array paths.
  8. function getPropertyByPath(source , path ) {
  9. if (typeof path === 'string' && source.hasOwnProperty(path)) {
  10. return source[path];
  11. }
  12. const parsedPath = typeof path === 'string' ? path.split('.') : path;
  13. return parsedPath.reduce((previous, key) => {
  14. if (previous === undefined) {
  15. return previous;
  16. }
  17. return previous[key];
  18. }, source);
  19. }
  20. module.exports = getPropertyByPath;