Skip to content

A tiny node module for parsing FormData by name into objects and arrays

License

Notifications You must be signed in to change notification settings

milamer/parse-nested-form-data

Repository files navigation

parse-nested-form-data

A tiny node module for parsing FormData by name into objects and arrays


Build Status Code Coverage version downloads MIT License All Contributors PRs Welcome Code of Conduct

The problem

  1. You use Forms to upload data to your server (e.g. with remix-run)
  2. You want a way to upload objects and arrays with booleans and numbers
  3. You do not want to transfer the data per hand

This solution

A parse functions that uses the name prop to tells the parser how to create an object out of the values. You can tell the parser to do not parse empty values.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install parse-nested-form-data

and then import it in your project:

import {parseFormData} from 'parse-nested-form-data'

Name

The name prop is used to tell the parser how to create an object out of the values. The name prop is a string that can contain the following characters:

  • .: to create a nested object
  • []: to create an array (pushes value)
  • [$order]: to create an array (sets value at index and squashes array)
  • &: to transform the value to a boolean
  • -: to transform the value to null
  • +: to transform the value to a number

Boolean

If the name prop starts with a & the value will be transformed to a boolean.

True if the value has the following values:

  • true
  • 1
  • on
const formData = new FormData()
formData.append('&isTrue', 'true')
formData.append('&isFalse', 'false')
formData.append('&isTrue1', '1')
formData.append('&isFalse1', '0')
formData.append('&isTrue2', 'on')
formData.append('&isFalse2', 'off')
parseFormData(formData)
// {
//   isTrue: true,
//   isFalse: false,
//   isTrue1: true,
//   isFalse1: false,
//   isTrue2: true,
//   isFalse2: false,
// }

Number

If the name prop starts with a + the value will be transformed to a number.

const formData = new FormData()
formData.append('+number', '1')
formData.append('+number2', '1.1')
formData.append('+number3', 'a')
parseFormData(formData)
// {
//   number: 1,
//   number2: 1.1,
//   number3: NaN,
// }

Null

If the name prop starts with a - the value will be transformed to null.

const formData = new FormData()
formData.append('-null', 'null')
formData.append('-ignored', 'ignored')
parseFormData(formData)
// {
//   null: null,
//   ignored: null,
// }

Array

If a path of the name prop ends with [] the value will be pushed to an array. If the path of the name prop ends with [$order] the value will be set at the index of the order. Cannot be mixed with [].

const formData = new FormData()
formData.append('array[0]', '1')
formData.append('array[1]', '2')
formData.append('array[2]', '3')
formData.append('array[3]', '4')
parseFormData(formData)
// {
//   array: ['1', '2', '3', '4'],
// }
const formData = new FormData()
formData.append('array[]', '1')
formData.append('array[]', '2')
formData.append('array[]', '3')
parseFormData(formData)
// {
//   array: ['1', '2', '3'],
// }

Also works with nested objects:

const formData = new FormData()
formData.append('array[0].a', '1')
formData.append('array[1].a', '2')
formData.append('array[2].a', '3')
parseFormData(formData)
// {
//   array: [{a: '1'}, {a: '2'}, {a: '3'}],
// }

Also works with nested arrays:

const formData = new FormData()
formData.append('array[0][]', '1')
formData.append('array[0][]', '2')
formData.append('array[1][]', '3')
formData.append('array[1][]', '4')
parseFormData(formData)
// {
//   array: [['1', '2'], ['3', '4']],
// }

Object

If the name prop contains a . the value will be nested in an object.

const formData = new FormData()
formData.append('object.a', '1')
formData.append('object.b', '2')
parseFormData(formData)
// {
//   object: {
//     a: '1',
//     b: '2',
//   },
// }

Basic Usage

Transform values

const formData = new FormData()
formData.append('+a', '1')
formData.append('&b', 'true')
formData.append('-c', 'null')
formData.append('d', 'foo')
parseFormData(formData, defaultTransform)
// => {a: 1, b: true, c: null, d: 'foo'}

Advanced usage

Complex examples:

const formData = new FormData()
formData.append('a[].b.c', '1')
formData.append('a[].b.d', '2')
formData.append('a[]', '3')
formData.append('b[0]', '4')
formData.append('+b[100]', '5')
parseFormData(formData)
// {
//   a: [
//     {
//       b: {
//         c: '1',
//         d: '2',
//       },
//     },
//     '3',
//   ],
//   b: ['4', 5],
// }

Options

The second argument is an option object with following properties:

removeEmptyString: [boolean]

Default: false

If true empty strings will be removed from the result.

const formData = new FormData()
formData.append('foo[1].foo', '')
formData.append('foo[1].bar', 'test2')
formData.append('foo[0].foo', 'test3')
formData.append('foo[0].baz', '4')

parseFormData(formData, {removeEmptyString: true})
// {foo: [{foo: 'test3', baz: '4'}, {bar: 'test2'}]}

transformEntry: (entry: [path: string, value: string | File], defaultTransform: DefaultTransform) => [string, string | JsonLeafValue]

const formData = new FormData()
formData.append('a', 'a')
formData.append('b', 'b')
parseFormData(formData, {
  transformEntry: ([path, value], defaultTransform) => {
    return {
      path,
      value:
        typeof value === 'string'
          ? value.toUpperCase()
          : defaultTransform(value),
    }
  },
})
// => {a: 'A', b: 'B'}

Issues

Looking to contribute? Look for the Good First Issue label.

πŸ› Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

πŸ’‘ Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a πŸ‘. This helps maintainers prioritize what to work on.

See Feature Requests

Contributors ✨

Thanks goes to these people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

Special Thanks

Special thanks to Kent C. Dodds and his match-sorter package where most of the setup is from.

About

A tiny node module for parsing FormData by name into objects and arrays

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published