getobject.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * getobject
  3. * https://github.com/cowboy/node-getobject
  4. *
  5. * Copyright (c) 2013 "Cowboy" Ben Alman
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. var getobject = module.exports = {};
  10. // Split strings on dot, but only if dot isn't preceded by a backslash. Since
  11. // JavaScript doesn't support lookbehinds, use a placeholder for "\.", split
  12. // on dot, then replace the placeholder character with a dot.
  13. function getParts(str) {
  14. return str.replace(/\\\./g, '\uffff').split('.').map(function(s) {
  15. return s.replace(/\uffff/g, '.');
  16. });
  17. }
  18. // Get the value of a deeply-nested property exist in an object.
  19. getobject.get = function(obj, parts, create) {
  20. if (typeof parts === 'string') {
  21. parts = getParts(parts);
  22. }
  23. var part;
  24. while (typeof obj === 'object' && obj && parts.length) {
  25. part = parts.shift();
  26. if (!(part in obj) && create) {
  27. obj[part] = {};
  28. }
  29. obj = obj[part];
  30. }
  31. return obj;
  32. };
  33. // Set a deeply-nested property in an object, creating intermediary objects
  34. // as we go.
  35. getobject.set = function(obj, parts, value) {
  36. parts = getParts(parts);
  37. if (parts.includes('__proto__')) {
  38. // do not allow setting of __proto__. See CVE-2020-28282.
  39. return;
  40. }
  41. var prop = parts.pop();
  42. obj = getobject.get(obj, parts, true);
  43. if (obj && typeof obj === 'object') {
  44. return (obj[prop] = value);
  45. }
  46. };
  47. // Does a deeply-nested property exist in an object?
  48. getobject.exists = function(obj, parts) {
  49. parts = getParts(parts);
  50. var prop = parts.pop();
  51. obj = getobject.get(obj, parts);
  52. return typeof obj === 'object' && obj && prop in obj;
  53. };