Why Indices:true in object-to-formdata Matters


If you’re sending arrays to a backend API via FormData, the difference between indices: true and indices: false can break your integration—or fix it.

The Problem

When you convert a JavaScript object with arrays to FormData, you get different key formats depending on whether indices are enabled:

Without indices: true:

items[]=a&items[]=b&items[]=c

With indices: true:

items[0]=a&items[1]=b&items[2]=c

Both look reasonable. But here’s where things break: many backend frameworks handle these differently.

Why the Index Format Matters

1. Framework Consistency

PHP’s $_POST automatically handles items[]. But .NET, Django, and Express (without configuration) may expect explicit indices. The indices: true option ensures predictable key naming across frameworks.

2. Order Preservation

Explicit indices guarantee array order, even if the request gets reordered somewhere in the pipeline. With items[], you’re relying on the backend to parse them in order—and some don’t.

3. Partial Updates

When updating specific array elements (say, updating only items[1]), you need indices. Without them, there’s no way to target a single index in the array.

The Fix

It’s a one-line change:

const options = {
    indices: true, // This enables explicit indices: items[0], items[1]
};

const formData = objectToFormData(data, options);

When to Skip It

If you’re certain your backend handles items[] correctly and you’re not doing partial updates, you can skip it. But if you ever see “undefined” values in your array on the server side, or if different environments behave differently—this is likely why.


Tags: #JavaScript #FormData #API #WebDevelopment