npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

parse-nested-form-data

v1.0.0

Published

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

Downloads

9,238

Readme


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

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.