get.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. * @api private
  6. */
  7. module.exports = function get(obj, path, def) {
  8. let parts;
  9. let isPathArray = false;
  10. if (typeof path === 'string') {
  11. if (path.indexOf('.') === -1) {
  12. const _v = getProperty(obj, path);
  13. if (_v == null) {
  14. return def;
  15. }
  16. return _v;
  17. }
  18. parts = path.split('.');
  19. } else {
  20. isPathArray = true;
  21. parts = path;
  22. if (parts.length === 1) {
  23. const _v = getProperty(obj, parts[0]);
  24. if (_v == null) {
  25. return def;
  26. }
  27. return _v;
  28. }
  29. }
  30. let rest = path;
  31. let cur = obj;
  32. for (const part of parts) {
  33. if (cur == null) {
  34. return def;
  35. }
  36. // `lib/cast.js` depends on being able to get dotted paths in updates,
  37. // like `{ $set: { 'a.b': 42 } }`
  38. if (!isPathArray && cur[rest] != null) {
  39. return cur[rest];
  40. }
  41. cur = getProperty(cur, part);
  42. if (!isPathArray) {
  43. rest = rest.substr(part.length + 1);
  44. }
  45. }
  46. return cur == null ? def : cur;
  47. };
  48. function getProperty(obj, prop) {
  49. if (obj == null) {
  50. return obj;
  51. }
  52. if (obj instanceof Map) {
  53. return obj.get(prop);
  54. }
  55. return obj[prop];
  56. }