Skip to content

Commit

Permalink
Fix #119: Fix constructing more complex object with arrays (#126)
Browse files Browse the repository at this point in the history
* Group FormData parameters before restoring hx-vals/hx-vars type, to prevent duplicating arrays elements in final object

* Simplify

---------

Co-authored-by: Vincent <vichenzo-thebaud@hotmail.com>
  • Loading branch information
meex28 and Telroshan authored Jan 5, 2025
1 parent f3bb31e commit b0f44b2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
13 changes: 8 additions & 5 deletions src/json-enc/json-enc.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,24 @@
encodeParameters: function(xhr, parameters, elt) {
xhr.overrideMimeType('text/json')

const vals = api.getExpressionVars(elt)
const object = {}
parameters.forEach(function(value, key) {
// FormData encodes values as strings, restore hx-vals/hx-vars with their initial types
const typedValue = Object.hasOwn(vals, key) ? vals[key] : value
if (Object.hasOwn(object, key)) {
if (!Array.isArray(object[key])) {
object[key] = [object[key]]
}
object[key].push(typedValue)
object[key].push(value)
} else {
object[key] = typedValue
object[key] = value
}
})

const vals = api.getExpressionVars(elt)
Object.keys(object).forEach(function(key) {
// FormData encodes values as strings, restore hx-vals/hx-vars with their initial types
object[key] = Object.hasOwn(vals, key) ? vals[key] : object[key]
})

return (JSON.stringify(object))
}
})
Expand Down
3 changes: 2 additions & 1 deletion src/json-enc/test/ext/json-enc.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ describe('json-enc extension', function() {
xhr.respond(200, {}, 'clicked')
})

make(`<form hx-ext="json-enc" hx-post="/test" hx-vals="js:{'obj': {'x': 123}, 'number': 5000, 'numberString': '5000'}">
make(`<form hx-ext="json-enc" hx-post="/test" hx-vals="js:{'obj': {'x': 123}, 'number': 5000, 'numberString': '5000', 'array': ['text', 123, {'key': 'value'}]}">
<button id="btn" type="submit">Submit</button>
</form>`)
var btn = byId('btn')
Expand All @@ -153,6 +153,7 @@ describe('json-enc extension', function() {
values.number.should.equal(5000)
values.numberString.should.equal('5000')
chai.assert.deepEqual(values.obj, {'x': 123})
chai.assert.deepEqual(values.array, ['text', 123, {'key': 'value'}])
})

it('handles multiple values per key', function() {
Expand Down

0 comments on commit b0f44b2

Please sign in to comment.