diff --git a/CHANGELOG.md b/CHANGELOG.md index 7037ef3..fd94ac7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to the library will be documented in this file. ## vX.X.X (Month DD, YYYY) - Add `FormDataInfo` type to global exports +- Add support for non-indexed array fields (issue #8) ## v0.4.0 (November 12, 2023) diff --git a/src/decode.test.ts b/src/decode.test.ts index d7f30b6..ae32709 100644 --- a/src/decode.test.ts +++ b/src/decode.test.ts @@ -60,7 +60,7 @@ describe('decode', () => { expect(decode(formData, { files: ['file'] })).toEqual({ file }); }); - test('should decode arrays', () => { + test('should decode indexed arrays', () => { const formData = new FormData(); formData.append('array.0', 'index_0'); formData.append('array.1', 'index_1'); @@ -70,6 +70,20 @@ describe('decode', () => { }); }); + test('should decode non-indexed arrays', () => { + const formData = new FormData(); + formData.append('array', 'index_0'); + formData.append('array', 'index_1'); + formData.append('array', 'index_2'); + expect( + decode(formData, { + arrays: ['array'], + }) + ).toEqual({ + array: ['index_0', 'index_1', 'index_2'], + }); + }); + test('should decode objects', () => { const formData = new FormData(); formData.append('nested.string', 'hello'); diff --git a/src/decode.ts b/src/decode.ts index 31e7a9d..d3b8997 100644 --- a/src/decode.ts +++ b/src/decode.ts @@ -46,7 +46,21 @@ export function decode< !info?.files?.includes(templateName) || (value && (typeof value === 'string' || value.size)) ) { - object[key] = getFieldValue(info, templateName, value); + // Get field value + const fieldValue = getFieldValue(info, templateName, value); + + // If it is an non-indexed array, add value to array + if (info?.arrays?.includes(templateName)) { + if (object[key]) { + object[key].push(fieldValue); + } else { + object[key] = [fieldValue]; + } + + // Otherwise, add value directly to key + } else { + object[key] = fieldValue; + } } }, values); }