flattenObjectWithDottedPaths.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. const MongooseError = require('../../error/mongooseError');
  3. const setDottedPath = require('../path/setDottedPath');
  4. const util = require('util');
  5. /**
  6. * Given an object that may contain dotted paths, flatten the paths out.
  7. * For example: `flattenObjectWithDottedPaths({ a: { 'b.c': 42 } })` => `{ a: { b: { c: 42 } } }`
  8. */
  9. module.exports = function flattenObjectWithDottedPaths(obj) {
  10. if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) {
  11. return;
  12. }
  13. // Avoid Mongoose docs
  14. if (obj.$__) {
  15. return;
  16. }
  17. const keys = Object.keys(obj);
  18. for (const key of keys) {
  19. const val = obj[key];
  20. if (key.indexOf('.') !== -1) {
  21. try {
  22. delete obj[key];
  23. setDottedPath(obj, key, val);
  24. } catch (err) {
  25. if (!(err instanceof TypeError)) {
  26. throw err;
  27. }
  28. throw new MongooseError(`Conflicting dotted paths when setting document path, key: "${key}", value: ${util.inspect(val)}`);
  29. }
  30. continue;
  31. }
  32. flattenObjectWithDottedPaths(obj[key]);
  33. }
  34. };