1var object = {};
2formData.forEach(function(value, key){
3 object[key] = value;
4});
5var json = JSON.stringify(object);
6
7// Or ES6 arrow function
8var object = {};
9formData.forEach((value, key) => object[key] = value);
10var json = JSON.stringify(object);
11
1function buildFormData(formData, data, parentKey) {
2 if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
3 Object.keys(data).forEach(key => {
4 buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
5 });
6 } else {
7 const value = data == null ? '' : data;
8
9 formData.append(parentKey, value);
10 }
11}
12
13function jsonToFormData(data) {
14 const formData = new FormData();
15
16 buildFormData(formData, data);
17
18 return formData;
19}
20
21const my_data = {
22 num: 1,
23 falseBool: false,
24 trueBool: true,
25 empty: '',
26 und: undefined,
27 nullable: null,
28 date: new Date(),
29 name: 'str',
30 another_object: {
31 name: 'my_name',
32 value: 'whatever'
33 },
34 array: [
35 {
36 key1: {
37 name: 'key1'
38 }
39 }
40 ]
41};
42
43jsonToFormData(my_data)
44
1var object = {};
2formData.forEach(function(value, key){
3 object[key] = value;
4});
5var json = JSON.stringify(object);
6
1`const formDataObject = (formData) => {
2
3for (const key in formData) {
4 if (formData[key].startsWith('{') || formData[key].startsWith('[')) {
5 try {
6 formData[key] = JSON.parse(formData[key]);
7 console.log("key is :", key, "form data is :", formData[key]);
8
9 } catch (error) {
10 console.log("error :", key);
11 }
12 }
13}
14
15console.log("object", formData)
16}`
17