Skip to content

Commit

Permalink
Add support for non-indexed array fields #8
Browse files Browse the repository at this point in the history
  • Loading branch information
fabian-hiller committed Dec 15, 2023
1 parent 62a86c5 commit 7763810
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
16 changes: 15 additions & 1 deletion src/decode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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');
Expand Down
16 changes: 15 additions & 1 deletion src/decode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 7763810

Please sign in to comment.