Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@octetstream/object-to-form-data

Package Overview
Dependencies
Maintainers
0
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@octetstream/object-to-form-data

Serialize objects, arrays and collections into FormData.

  • 3.0.5
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
949
decreased by-21.96%
Maintainers
0
Weekly downloads
 
Created
Source

object-to-form-data

Serialize objects, arrays and collections into FormData.

Code Coverage CI

Installation

pnpm:

pnpm add @octetstream/object-to-form-data

npm:

npm i @octetstream/object-to-form-data

CJS/ESM support

This module supports both CommonJS and ES Modules.

Usage

  1. To use this package, just import objectToFormData and pass input data as the first argument:
import {objectToFormData} from "@octetstream/object-to-form-data"

const user = {
  name: "The Octocat",
  login: "octocat",
  url: "https://github.com/octocat",
  repositories: {
    nodes: [
      {
        name: "Hello-World",
        description: "My first repository on GitHub!",
        url: "https://github.com/octocat/Hello-World"
      }
    ]
  }
}

// You will receive a FormData instance with all fields of given object
const form = objectToFormData(user)

const options = {
  method: "post",
  body: form
}

const response = await fetch("https://httpbin.org/post", options)

The user object from this example will be serailized into FormData with following structure (pseudo code):

name = "The Octocat"
login = "octocat"
url = "https://github.com/octocat"
repositories[nodes][0][name] = "Hello-World"
repositories[nodes][0][description] = "My first repository on GitHub!"
repositories[nodes][0][url] = "https://github.com/octocat/Hello-World"
  1. By default the bracked notation is applied, but use can pass dot as notation option like this:
import {objectToFormData} from "@octetstream/object-to-form-data"

const person = {
  name: "Nick K.",
  url: "https://github.com/octet-stream",
  skills: ["TypeScript", "JavaScript", "React", "Next.js", "Vue", "Nuxt", "Qwik", "Docker"]
}

const form = objectToFormData(person, {
  notation: "dot" // This will enable dot notation for serialization
})

Returned form object has following structure:

name = "Nick K."
url = "https://github.com/octet-stream"
skills.0 = TypeScript
skills.1 = JavaScript
skills.2 = React
skills.3 = Next.js
skills.4 = Vue
skills.5 = Nuxt
skills.6 = Qwik
skills.7 = Docker
  1. You can also pass collections as the input:
import {objectToFormData} from "@octetstream/object-to-form-data"

const developers = [
  {
    name: "John Doe",
    skills: ["JavaScript", "TypeScript", "React", "Qwik"],
    isHireable: true
  },
  {
    name: "Max Doe",
    skills: ["Python", "Django", "Flask", "MySQL", "Pony ORM"],
    isHireable: false
  }
]

const form = objectToFormData(developers)

This results in following form structure:

[0][name] = "John Doe"
[0][skills][0] = "JavaScript"
[0][skills][1] = "TypeScript"
[0][skills][2] = "React"
[0][skills][3] = "Qwik"
[1][name] = "Max Doe"
[1][skills][0] = "Python"
[1][skills][1] = "Django"
[1][skills][2] = "Flask"
[1][skills][3] = "MySQL"
[1][skills][4] = "Pony ORM"
  1. Flat arrays supported too:
import {objectToFormData} from "@octetstream/object-to-form-data"

const fruits = ["orange", "pineapple", "nectarine", "pear", "pomegranate"]

const form = objectToFormData(fruits)

Result:

[0] = "orange"
[1] = "pineapple"
[2] = "nectarine"
[3] = "pear"
[4] = "pomegranate"
  1. Serializing files and blobs:
import {objectToFormData} from "@octetstream/object-to-form-data"

const input = [
  {
    caption: "Text file created with File object",
    file: new File(["My hovercraft if full of eels"], "test.txt", {type: "text/plain"}),
  },
  {
    caption: "Text data created with Blob object",
    file: new Blob(["On Soviet Moon landscape see binoculars through you"], {type: "text/plain"}),
  }
]

const form = objectToFormData(input)

Result:

[0][caption] = "Text file created with File object"
[0][file] = File [type: "text/plain", name: "test.txt", content: "My hovercraft if full of eels"]
[1][caption] = "Text data created with Blob object"
[1][file] = File [type: "text/plain", name: "blob", content: "On Soviet Moon landscape see binoculars through you"]

API

objectToFormData(input[, options]): FormData

Serializes objects, arrays and collections into FormData.

Nested objects will be flattened using either dot or bracket notation.

This function takes following arguments:

NameTypeRequiredDefaultDescription
inputunknown[] | Record<sting | number, unknown>trueAn object to transform
optionsObjectToFormDataOptionsfalseundefinedAdditional serialization options

Returns FormData instance.

interface ObjectToFormDataOptions

Serialization options

NameTypeRequiredDefaultDescription
strictbooleanfalsefalseIndicates whether or not to omit every false values. Applied enabled. Does not affect boolean array values
FormDataFormDatafalseglobalThis.FormDataCustom spec-compliant FormData implementation
notation"dot" | "bracket"false"bracket"Type of the nested fields notation. Can be either "dot" or "bracket"
normalizeValueNormalizeValuefalseundefinedValue normalizer. This function will be called on each scalar value, before it's added to FormData instance

interface NormalizeValue

Value normalizer.

A function to be called on each scalar value, before it's added to FormData instance. It must return either Blob or string

This function will be called with the following arguments:

NameTypeDescription
valueunknownCurrent entry value
namestringThe name of the entry
pathArray<string | number>Entry's path within original object

This function must return either Blob or string. Any unsupported type will be converted to string by FormData.

  • FormData documentation on MDN
  • File documentation on MDN
  • Blob documentation on MDN
  • FormDataValue documentation on MDN.
  • formdata-node Spec-compliant FormData implementation for Node.js.
  • formdata-polyfill HTML5 FormData for Browsers & NodeJS.
  • node-fetch a light-weight module that brings the Fetch API to Node.js
  • fetch-blob a Blob implementation for Node.js, originally from node-fetch.
  • form-data-encoder spec-compliant multipart/form-data encoder implementation.
  • then-busboy a promise-based wrapper around Busboy. Process multipart/form-data content and returns it as a single object. Will be helpful to handle your data on the server-side applications.

Keywords

FAQs

Package last updated on 21 Aug 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc