Skip to content

Simple indexed arrays like field[0] are not automatically detected as arrays #16

Description

@Kheirah

Currently, decode-formdata automatically detects arrays only when fields have nested properties like filters[0].code.
However, simple indexed fields like languages[0], languages[1] are treated as objects instead of arrays, requiring manual configuration in the arrays parameter.

Current behavior:

  • filters[0].code, filters[1].code → { filters: [{code: "..."}] } ✅
  • languages[0], languages[1] → { languages: {0: "...", 1: "..."} } ❌

Expected behavior:

  • Both patterns should automatically create arrays

Suggested fix:
Add detection for numeric indices at the last position:

decode.ts

if (index < keys.length - 1) {
  // If array or object already exists, return it
  if (current[key]) {
    current = current[key];

    // Otherwise, check if value is an array
  } else {
    const isArray =
      index < keys.length - 1 // change from 2 to 1
        ? templateKeys[index + 1] === '$'
        : info?.arrays?.includes(templateKeys.slice(0, -1).join('.'));

    // Add and return empty array or object
    current = current[key] = isArray ? [] : {};
  }

This would make the library more intuitive for common HTML form patterns without breaking existing functionality.

Additional test case:

test("should automatically create arrays", () => {
  const formData = new FormData();
  formData.append("languages[0]", "en");
  formData.append("languages[1]", "es");
  expect(decode(formData)).toStrictEqual({
    languages: ["en", "es"],
  });
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions