hongymagic/jQuery.serializeObject

Array names

Closed this issue · 3 comments

Inputs with array names like "foo[0]" are not converted to an array. Instead the literal string "foo[0]" is used as the property name.

Are they supposed to be? Consider the following HTML:

<form type="GET" action="">
    <label>Favourite heroes</label>
    <input type="checkbox" name="likes[]" value="Batman" />
    <input type="checkbox" name="likes[]" value="Superman" />
    <input type="checkbox" name="likes[]" value="HULK" />
    <input type="checkbox" name="likes[]" value="Captain America" />

    <button type="submit">Do it Vince!!</button>
</form>

When you click on submit, browser appends properties with name "likes[]". If this is the behaviour of $.serializeArray and browsers, I would leave it as-is. This plugin is a transformation of $.serializeArray, it shouldn't have to translate anything.

The likes inputs in the form you posted would already be converted to an array correctly:

{
    "likes": [
        "Batman",
        "Superman",
        "HULK",
        "Captain America"
    ]
}

I'm talking about when you throw in the index (a valid JSON array would be zero-indexed), it breaks. It's a pain if you ever want to link multiple arrays together, or provide an array of objects, like foo[0][bar] and then foo[0][baz], which you would expect back in the correct format:

{
    "foo": [
        {
            "bar": "...",
            "baz": "..."
        }
    ]
}

Instead you get:

{
    "foo[0][baz]": "...",
    "foo[0][bar]": "..."
}

@AdamBoxall check out jquery-serialize-plugin if you're looking for this type of functionality. It does exactly what you're expecting.