Home > Software engineering >  serialize a form (with inputs dynamic) for API call with JSON
serialize a form (with inputs dynamic) for API call with JSON

Time:06-04

I'm trying to serialize a web form to json with some js. I found examples but not exactly what I'm looking for.

In input I have this form

I found this function on stackoverflow.com almost meets my need, but I can't finalize (https://stackoverflow.com/a/25239999/1932025)

function formArrayConverter(formArray){
    var obj = {};
    $.each(formArray, function(i, pair){
        var cObj = obj, pObj, cpName;
        $.each(pair.name.split("."), function(i, pName){
            pObj = cObj;
            cpName = pName;
            cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
        });
        pObj[cpName] = pair.value;
    });
    return obj;
}


// I transform the form into a table with javascript
let myFormArray = $('#exampleForm').serializeArray();
console.log('the array:');
console.log(myFormArray);

// After calling the function I get this result in console
console.log('formArrayConverter(myFormArray) result : ');
console.log(formArrayConverter(myFormArray));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" id="exampleForm">
    <input type="hidden" name="Id" value="32468">
    <input type="datetime" name="EffectiveDate" value="2022-06-03">
    <input type="number"   name="TotalAmount" value="57.99">
    <input type="text" name="Manager.Name" value="ManagerName">
    <input type="text" name="Manager.Level" value="10">
    <!-- variable number of inputs --> 
    <input type="text" value="Phone" name="Categories[0].Name">
    <input type="number" name="Categories[0].Amount" value="47.99">
    <input type="text" value="Tax" name="Categories[1].Name">
    <input type="number" name="Categories[1].Amount" value="10.00">
    <!-- ... -->
</form>

** $('#exampleForm').serializeArray() return that before call function "formArrayConverter()" **

[
  {
    "name": "Id", "value": "32468"
  },
  {
    "name": "EffectiveDate", "value": "2022-06-03"
  },
  {
    "name": "TotalAmount", "value": "57.99"
  },
  {
    "name": "Manager.Name", "value": "ManagerName"
  },
  {
    "name": "Manager.Level", "value": "10"
  },
  {
    "name": "Categories[0].Name", "value": "Phone"
  },
  {
    "name": "Categories[0].Amount", "value": "47.99"
  },
  {
    "name": "Categories[1].Name", "value": "Tax"
  },
  {
    "name": "Categories[1].Amount", "value": "10.00"
  }
]

After calling the function "formArrayConverter" I get this result

{
    "Id": "32468",
    "EffectiveDate": "2022-06-03",
    "TotalAmount": "57.99",
    "Manager": {
        "Name": "ManagerName",
        "Level": "10"
    },
    "Categories[0]": {
        "Name": "Phone",
        "Amount": "47.99"
    },
    "Categories[1]": {
        "Name": "Tax",
        "Amount": "10.00"
    }
}

My problem comes from the serialization of the category array. I would like to have for my API call to work :

{
    "Id": "32468",
    "EffectiveDate": "2022-06-03",
    "TotalAmount": "57.99",
    "Manager": {
        "Name": "ManagerName",
        "Level": "10"
    },
    "Categories": [
        {
            "Name": "Phone",
            "Amount": "47.99"
        },
        {
            "Name": "Tax",
            "Amount": "10.00"
        }
    ]
}

My case is a simple example. I have several calls to make and I wanted to make a generic function. Thank you

CodePudding user response:

try this

var d= formArrayConverter(myFormArray);

for (const key in d) {
  var len = key.indexOf("[");
  if (len > 0) {
    var arrName = key.substring(0, len);
    if (!d.hasOwnProperty(arrName)) {
      d[arrName] = [];
    }
    d[arrName].push(d[key]);
    delete d[key];
  }
}
console.log(JSON.stringify(d);

you can move this code inside of formArrayConverter if it works for you.

  • Related