macek/jquery-serialize-object

Mixing 'pushed' and 'named' key styles doesn't work as expected

jeffsrepoaccount opened this issue · 2 comments

Sample Form:

<input type="text" name="test[foo]" value="42" />
<input type="text" name="test[]" value="12" />

Expected Output:

> $('#myForm').serializeObject();
{
    test: {
        0: 12,
        foo: 42
    }
}

Actual Output:

> $('#myForm').serializeObject();
{
    test: [ 12 ]
}

It seems that whichever form is used last is the one the plugin uses. Swap the order of input elements and the foo key will wind up being set instead.

The use-case is an edit form including a section of 'add more'-type functionality. In my case, the indices are UUID keys when the objects themselves are already created, indicating the server should edit those entries. They are blank when an add more button is clicked, indicating the server should create those entries. If there is an easy way to workaround this I would be much appreciative.

macek commented

Yeah, you found one of the niche opinionated behaviors I decided to yank from the plugin a long while back. In short, the plugin used to make an assumption about how to treat the mixture of numeric, named, and push keys. I'm not sure if it matched your expectation, but whatever the behavior was, it was completely straightforward or entirely intuitive. In lieu of a widespread need for the supported behavior, I pulled it in favor of the much more explicit "named keys are for {}" and "numeric/push keys are for []". It's not suitable for everyone, but conventionally, there is no way to "push" to an object and most people don't use numeric keys on objects, so it made sense at the time.

Check out #24 for some more details on this. The 3.x version of this plugin will be much more explicit on the matter of how to handle situations like the one you've presented. When that will be complete, I'm not sure. I simply haven't found the time to dedicate to it lately 😦


Aside from that, if you're willing/able to change the shape of your data, me and thousands of other people have used this plugin without issues.

Attach a small snippet of your actual form to show me the data you're intend to represent. I can try to show you a way to structure your form that works with this plugin.

FYI- I was able to easily work around this issue by changing how I use the keys:

<input type="text" name="test[uuid-key-for-existing-objects]" value="42" />
<input type="text" name="test[new][]" value="12" />

Now I can iterate over POST['new'] array in order to create new items and still be able to iterate over the rest of the keys to update existing ones. Thanks for the help macek, it pointed me in the right direction.