You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
775 B

4 years ago
  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;