formDataToJSON.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. import utils from '../utils.js';
  3. /**
  4. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  5. *
  6. * @param {string} name - The name of the property to get.
  7. *
  8. * @returns An array of strings.
  9. */
  10. function parsePropPath(name) {
  11. // foo[x][y][z]
  12. // foo.x.y.z
  13. // foo-x-y-z
  14. // foo x y z
  15. return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
  16. return match[0] === '[]' ? '' : match[1] || match[0];
  17. });
  18. }
  19. /**
  20. * Convert an array to an object.
  21. *
  22. * @param {Array<any>} arr - The array to convert to an object.
  23. *
  24. * @returns An object with the same keys and values as the array.
  25. */
  26. function arrayToObject(arr) {
  27. const obj = {};
  28. const keys = Object.keys(arr);
  29. let i;
  30. const len = keys.length;
  31. let key;
  32. for (i = 0; i < len; i++) {
  33. key = keys[i];
  34. obj[key] = arr[key];
  35. }
  36. return obj;
  37. }
  38. /**
  39. * It takes a FormData object and returns a JavaScript object
  40. *
  41. * @param {string} formData The FormData object to convert to JSON.
  42. *
  43. * @returns {Object<string, any> | null} The converted object.
  44. */
  45. function formDataToJSON(formData) {
  46. function buildPath(path, value, target, index) {
  47. let name = path[index++];
  48. if (name === '__proto__') return true;
  49. const isNumericKey = Number.isFinite(+name);
  50. const isLast = index >= path.length;
  51. name = !name && utils.isArray(target) ? target.length : name;
  52. if (isLast) {
  53. if (utils.hasOwnProp(target, name)) {
  54. target[name] = [target[name], value];
  55. } else {
  56. target[name] = value;
  57. }
  58. return !isNumericKey;
  59. }
  60. if (!target[name] || !utils.isObject(target[name])) {
  61. target[name] = [];
  62. }
  63. const result = buildPath(path, value, target[name], index);
  64. if (result && utils.isArray(target[name])) {
  65. target[name] = arrayToObject(target[name]);
  66. }
  67. return !isNumericKey;
  68. }
  69. if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
  70. const obj = {};
  71. utils.forEachEntry(formData, (name, value) => {
  72. buildPath(parsePropPath(name), value, obj, 0);
  73. });
  74. return obj;
  75. }
  76. return null;
  77. }
  78. export default formDataToJSON;