marioizquierdo / jquery.serializeJSON

Serialize an HTML Form to a JavaScript Object, supporting nested attributes and arrays.
MIT License
1.71k stars 433 forks source link

Is there something wrong about array? #110

Closed Tyxiang closed 3 years ago

Tyxiang commented 3 years ago

the form

<form>

    <input type="text" name="peoples[][name][first]:string" value="Liu" />
    <input type="text" name="peoples[][name][last]:string" value="Tom" />
    <input type="text" name="peoples[][age]:string" value="12" />

    <input type="text" name="peoples[][name][first]:string" value="Gao" />
    <input type="text" name="peoples[][name][last]:string" value="Jack" />
    <input type="text" name="peoples[][age]:string" value="15" />

</form>

desired result

{
    "peoples": [
        {
            "name": {
                "first": "Gao",
                "last": "Jack"
            },
            "age": "15"
        },
        {
            "name": {
                "first": "Liu",
                "last": "Tom"
            },
            "age": "12"
        }
    ]
}

actual result

{
    "peoples": [
        {
            "name": {
                "first": "Gao",
                "last": "Jack"
            },
            "age": "12"
        },
        {
            "age": "15"
        }
    ]
}
marioizquierdo commented 3 years ago

Seems like a bug. In the meantime, you can mitigate this by using an explicit index, and the option useIntKeysAsArrayIndex: true.

The form:

<form>
    <input type="text" name="peoples[0][name][first]:string" value="Liu" />
    <input type="text" name="peoples[0][name][last]:string" value="Tom" />
    <input type="text" name="peoples[0][age]:string" value="12" />

    <input type="text" name="peoples[1][name][first]:string" value="Gao" />
    <input type="text" name="peoples[1][name][last]:string" value="Jack" />
    <input type="text" name="peoples[1][age]:string" value="15" />
</form>

JavaScript call:

$('form').serializeJSON({useIntKeysAsArrayIndex: true});