getobject.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. var prop = parts.pop();
  38. obj = getobject.get(obj, parts, true);
  39. if (obj && typeof obj === 'object') {
  40. return (obj[prop] = value);
  41. }
  42. };
  43. // Does a deeply-nested property exist in an object?
  44. getobject.exists = function(obj, parts) {
  45. parts = getParts(parts);
  46. var prop = parts.pop();
  47. obj = getobject.get(obj, parts);
  48. return typeof obj === 'object' && obj && prop in obj;
  49. };