Object to FormData Serializer

4.5.1 · active · verified Sun Apr 19

object-to-formdata is a utility library for JavaScript that efficiently serializes plain JavaScript objects into `FormData` instances, a crucial browser API for sending data via `multipart/form-data` requests. Currently at version 4.5.1, it provides options to control how arrays, nulls, booleans, and object/array notation in keys are handled during serialization. The package is actively maintained with regular updates and bug fixes, indicated by its recent releases. Its primary differentiator is the configurable serialization logic, allowing developers to fine-tune how complex data structures are represented in `FormData` compared to manual construction or simpler serializers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic serialization of a complex JavaScript object, including files, arrays, and nested objects, into a FormData instance using various configuration options, and appending to existing FormData.

import { serialize } from 'object-to-formdata';

const userProfile = {
  name: 'John Doe',
  email: 'john.doe@example.com',
  age: 30,
  isActive: true,
  roles: ['admin', 'editor'],
  address: {
    street: '123 Main St',
    city: 'Anytown',
    zip: '12345'
  },
  avatar: new File([''], 'avatar.png', { type: 'image/png' })
};

const options = {
  indices: true, // Serialize roles[0]=admin, roles[1]=editor
  booleansAsIntegers: true, // Serialize isActive=1
  nullsAsUndefineds: true, // Ignore null values
  dotsForObjectNotation: false // Use brackets for objects (address[street])
};

const formData = serialize(userProfile, options);

// To see the contents (FormData is not directly iterable by value without special methods):
for (const pair of formData.entries()) {
  console.log(`${pair[0]}: ${pair[1]}`);
}

// Example of appending to an existing FormData instance
const existingData = new FormData();
existingData.append('tenantId', '123-abc');
const combinedFormData = serialize({ metadata: 'important' }, {}, existingData);

for (const pair of combinedFormData.entries()) {
  console.log(`Combined: ${pair[0]}: ${pair[1]}`);
}

view raw JSON →