macek/jquery-serialize-object

Double key value pairs supported?

EricWarnke opened this issue · 2 comments

I searched a bit but couldn't find a quick answer. FYI, love what is working so far!

Is processing into this format even possible with this plugin?

"entries": [
    {
      "id": 123,
      "value": "Some text"
    },
    {
      "id": 321,
      "value": "Other text"
    }
]

I can't find a way to ensure name="entries[id]" value="123" will group itself with name="entries[value]" value="Some text"

Is there a way to "group" values I want to stay together? Hopefully I'm just having a brain cramp.

macek commented
<!-- use a known index to group items together -->
<!-- starting with 0 -->
<input name="entres[0][id]" value="123">
<input name="entres[0][value]" value="Some text">
<!-- then 1 -->
<input name="entres[1][id]" value="321">
<input name="entres[1][value]" value="Other text">
<!-- then 2 -->
<input name="entres[2][id]" value="333">
<input name="entres[2][value]" value="Third text">
<!-- ... ->

If you have a dynamic form, you'll probably end up using a variable to keep track of that counter. Increment when the user clicks "add" where a new set of fields is added to the form.

// example
let counter = 0
$addEntry.click(() =>
  counter = counter + 1
  $form.append(`
    <input name="entres[${counter}][id]" value="">
    <input name="entres[${counter}][value]" value="">
  `)
)

Optional: decrement counter when an item is removed; this helps prevent creation of sparse arrays

Is this what you were looking for?

Ah, that's great. Thanks so much!