Andrei Cristian Prodan Andrei Cristian Prodan - 3 months ago 8
jQuery Question

How do you JSON (instead of serialize) a form that has name="Item[][things]" without obtaining an object with null children?

This is a pretty specific issue and I can't find it online or I couldn't find a solution to it until now at least.

I have a form, that contains inputs that have:

name = "Item[][things]"
as in an item. Can't change that. I want to turn that into a JSON to send it to the server. I can't use serialize, I really need to turn it into a JSON.

This doesn't work with what I tried:
JSON.stringify($myForm.serializeObject())
. Because my form contains name="Item[][differentOtherThings]", I get an array of nulls
[null, null, ..., null]


I added a serializeObject() custom method jquery-serialize-object to my project.

Any ideas on how I could JSON the form without the null issue?

Answer

see the bellow snippet

$(function(){
  $("#serialize").click(function(){
    var $myForm = $("form").eq(0);
    var str = JSON.stringify($myForm.serializeObject());
    console.log(str);
    var object = JSON.parse(str);
    console.log(object);
  })
});

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form>
   <p><input type="text"  name = "Item[][things]"></p>
   <p><input type="text"  name = "Item[][things1]"></p> 
   <p><input type="text"  name = "Item[][differentOtherThings]"></p>

</form>

  <button id="serialize">serialize</button>