get.js 1.2 KB

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