dotize.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Convert complex js object to dot notation js object
  2. // url: https://github.com/vardars/dotize
  3. // author: vardars
  4. var dotize = dotize || {};
  5. dotize.convert = function(obj, prefix) {
  6. var newObj = {};
  7. if ((!obj || typeof obj != "object") && !Array.isArray(obj)) {
  8. if (prefix) {
  9. newObj[prefix] = obj;
  10. return newObj;
  11. } else {
  12. return obj;
  13. }
  14. }
  15. function isNumber(f) {
  16. return !isNaN(parseInt(f));
  17. }
  18. function isEmptyObj(obj) {
  19. for (var prop in obj) {
  20. if (Object.hasOwnProperty.call(obj, prop))
  21. return false;
  22. }
  23. }
  24. function getFieldName(field, prefix, isRoot, isArrayItem, isArray) {
  25. if (isArray)
  26. return (prefix ? prefix : "") + (isNumber(field) ? "[" + field + "]" : (isRoot ? "" : ".") + field);
  27. else if (isArrayItem)
  28. return (prefix ? prefix : "") + "[" + field + "]";
  29. else
  30. return (prefix ? prefix + "." : "") + field;
  31. }
  32. return function recurse(o, p, isRoot) {
  33. var isArrayItem = Array.isArray(o);
  34. for (var f in o) {
  35. var currentProp = o[f];
  36. if (currentProp && typeof currentProp === "object") {
  37. if (Array.isArray(currentProp)) {
  38. newObj = recurse(currentProp, getFieldName(f, p, isRoot, false, true), isArrayItem); // array
  39. } else {
  40. if (isArrayItem && isEmptyObj(currentProp) == false) {
  41. newObj = recurse(currentProp, getFieldName(f, p, isRoot, true)); // array item object
  42. } else if (isEmptyObj(currentProp) == false) {
  43. newObj = recurse(currentProp, getFieldName(f, p, isRoot)); // object
  44. } else {
  45. //
  46. }
  47. }
  48. } else {
  49. if (isArrayItem || isNumber(f)) {
  50. newObj[getFieldName(f, p, isRoot, true)] = currentProp; // array item primitive
  51. } else {
  52. newObj[getFieldName(f, p, isRoot)] = currentProp; // primitive
  53. }
  54. }
  55. }
  56. return newObj;
  57. }(obj, prefix, true);
  58. };
  59. dotize.stringify = function(object) {
  60. var dotObj = dotize.convert(object);
  61. }
  62. if (typeof module != "undefined") {
  63. module.exports = dotize;
  64. }