Guest User

Untitled

a guest
Jan 20th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. // convert plain object to dot notation
  2. // For example the following object:
  3. /*
  4. const obj = {
  5. app: {
  6. lang: {
  7. menu: {
  8. welcome: "welcome",
  9. label: "label"
  10. },
  11. sensor: "sensor",
  12. sensors: {
  13. headline: "headline",
  14. text: "text"
  15. }
  16. }
  17. }
  18. }
  19. */
  20. // converts to:
  21. /*
  22. [
  23. "app.lang.menu.welcome",
  24. "app.lang.menu.label",
  25. "app.lang.menu.sensor",
  26. "app.lang.menu.sensors.headline",
  27. "app.lang.menu.sensors.text"
  28. ]
  29. */
  30.  
  31. // IE11 compatiple version
  32.  
  33. function ObjectToDotNotation(obj, dots, dot) {
  34. if(typeof obj === 'string') return obj;
  35. if(!dots) dots = [];
  36. if(!dot) dot = "";
  37. for(var key in obj) {
  38. var val = obj[key];
  39. var isObject = val != null && typeof val === 'object' && Array.isArray(val) === false;
  40. if (isObject) {
  41. dot += dot ? '.' + key : key;
  42. ObjectToDotNotation(val, dots, dot);
  43. } else if (typeof val === 'string') {
  44. dots.push(dot + '.' + key);
  45. }
  46. }
  47. return dots;
  48. }
  49.  
  50. // ES6 version, not compatible with older browsers
  51.  
  52. function ObjectToDotNotation(obj, dots = [], dot = "") {
  53. if (typeof obj === 'string') {
  54. return obj;
  55. }
  56. Object.keys(obj).forEach((key) => {
  57. let val = obj[key];
  58. if (val != null && typeof val === 'object' && Array.isArray(val) === false) {
  59. dot += dot ? `.${key}` : key
  60. ObjectToDotNotation(val, dots, dot);
  61. } else if (typeof val === 'string') {
  62. dots.push(`${dot}.${key}`);
  63. }
  64. });
  65. return dots;
  66. }
Add Comment
Please, Sign In to add comment