DarcCode DarcCode - 3 months ago 27
JSON Question

jQuery Form - Serialize into multi dimensional array?

I need to get value from

form
, format it to JSON and post it via AJAX. This is the format I want to achieve:

{
items: [
{ id: 7, name: 'Book', price: 5.7 },
{ id: 5, name: 'Pencil', price: 2.5 }
]
}


Here's the HTML:



(function($){

var $form = $('form');

// serializeArray format is way off from what I need
var rawData = $form.serializeArray();
console.log(rawData)

})(jQuery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset>
<h2>Product 1</h2>
<input type="hidden" name="items[0][id]" value="7">
<input type="text" name="items[0][name]" value="Book">
<input type="number" name="items[0][price]" value="5.7">
</fieldset>

<fieldset>
<h2>Product 2</h2>
<input type="hidden" name="items[1][id]" value="5">
<input type="text" name="items[1][name]" value="Pencil">
<input type="number" name="items[1][price]" value="2.5">
</fieldset>
</form>





Should I loop and use regex to parse the
name
? or is there built-in way?

I can change the
<form>
format if needed.

Answer

Please take a look at this approach. We can't just use $.serializeArray() but also we need some custom code as follows. Actually we need to iterate over all <fieldset> to get JSON as we needed:

(function($) {

  var $form = $('form');
  var fieldSets = $form.find("fieldset");
  var result = {
    items: []
  };
  fieldSets.each(function() {
    var fields = {};
    $.each($(this).serializeArray(), function() {
      fields[this.name] = this.value;
    });
    result.items.push(fields);
  });

  console.log(result);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <fieldset>
    <h2>Product 1</h2>
    <input type="hidden" name="id" value="7">
    <input type="text" name="name" value="Book">
    <input type="number" name="price" value="5.7">
  </fieldset>

  <fieldset>
    <h2>Product 2</h2>
    <input type="hidden" name="id" value="5">
    <input type="text" name="name" value="Pencil">
    <input type="number" name="price" value="2.5">
  </fieldset>
</form>

Note: Modified the HTML a bit as instead of name="items[0][id]" i have given as name="id"