milamer / parse-nested-form-data

A tiny node module for parsing FormData by name into objects and arrays
MIT License
43 stars 2 forks source link

"Duplicate key" error when parsing array-like field with non-numeric key #2

Open michaelrog opened 1 year ago

michaelrog commented 1 year ago

Thanks so much for this package!

We're trying to parse FormData from fields that contain associative-array content:

<input type="hidden" name="myField[foo]" value="1">
<input type="hidden" name="myField[bar]" value="2>

Minimal reproduction:

import {parseFormData} from 'parse-nested-form-data'

const formData = new FormData()
formData.append('myField[foo]', '1')
formData.append('myField[bar]', '2')
parseFormData(formData)

Using string keys with array fields like this produces a "Duplicate key" error:

Uncaught Error: Duplicate key at path part array[foo]
    DuplicateKeyError parse-nested-form-data.esm.js:42
    handlePathPart parse-nested-form-data.esm.js:237
    parseFormData parse-nested-form-data.esm.js:363
    parseFormData parse-nested-form-data.esm.js:362

I'm not surprised to see an error here, since JS [] arrays are integer-indexed, but... Given that string-keyed "array" fields are pretty common in forms/apps these days, could parseFormData() be somehow clever enough to parse these entries into a map object instead of a numeric-keyed array?

jwnx commented 1 year ago

I can send a fix if the maintainer is okay with this.

WildEgo commented 1 year ago

I can send a fix if the maintainer is okay with this.

Hey not the maintainer but could u fork and post it? Would be nice even if the PR doesn't get accepted

JClackett commented 5 days ago

any updates on this? I guess the issue is what would the output data structure be? because when its index based the "key" is built into the fact its an array, but where/how do you store the key if its a random string?