source: frontend/node_modules/axios/lib/helpers/formDataToJSON.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago

Fix frontend appearance

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