get.js 783 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. /*!
  3. * Simplified lodash.get to work around the annoying null quirk. See:
  4. * https://github.com/lodash/lodash/issues/3659
  5. */
  6. module.exports = function get(obj, path, def) {
  7. const parts = path.split('.');
  8. let rest = path;
  9. let cur = obj;
  10. for (const part of parts) {
  11. if (cur == null) {
  12. return def;
  13. }
  14. // `lib/cast.js` depends on being able to get dotted paths in updates,
  15. // like `{ $set: { 'a.b': 42 } }`
  16. if (cur[rest] != null) {
  17. return cur[rest];
  18. }
  19. cur = getProperty(cur, part);
  20. rest = rest.substr(part.length + 1);
  21. }
  22. return cur == null ? def : cur;
  23. };
  24. function getProperty(obj, prop) {
  25. if (obj == null) {
  26. return obj;
  27. }
  28. if (obj instanceof Map) {
  29. return obj.get(prop);
  30. }
  31. return obj[prop];
  32. }