macek/jquery-serialize-object

Push objects to array (regex modification?)

Artemis909 opened this issue · 2 comments

Hi there, I would like to make following JSON request

[
  {
    "name": "",
    "address": {
      "street": "",
      "number": "",
    }
  },
  {
    "name": "",
    "address": {
      "street": "",
      "number": "",
    }
  }
]

Unfortunately following inputs not working

           <input id="name-1" name="[0][name]" type="text"/>
           <input id="name-2" name="[1][name]" type="text"/>

Any idea how to done thsi task? I am not sure but maybe modification of regex would help in this case.

macek commented

Because HTML forms are key/value, the plugin will only serialize the form to an object {} of key/value pairs, not an array []. You can serialize arrays, but only as values in the root object.

You need at least one root key in your form. For example, in your form, I might use the root, contacts

Try something like inputs with the following names

contacts[0][name]
contacts[0][address][street]
contacts[0][address][number]
contacts[1][name]
contacts[1][address][street]
contacts[1][address][number]
...

The resulting structure will be

{
  contacts: [
    {
      "name": "",
      "address": {
        "street": "",
        "number": "",
      }
    },
    {
      "name": "",
      "address": {
        "street": "",
        "number": "",
      }
    }
  ]
}

Ok, thak you very much.