Methods
formDataToObject(formDataOrForm) → {Object}
Constructs a plain object from an existing FormData object or a given form element.
The idea of this function is, to make working with form data easier in programmatic contexts by allowing operations like optional chaining and "in" operators. This might especially come in handy if you need to do programmatic validations.
Additionally, this function streamlines field names, by discarding PHP-style array field name conventions like "files[]", by removing the brackets. So, if you have a field named "files[]" and another field named "files", both will just end up in one "files"-field, having an array as a value containing all combined values.
Keep in mind, that the status of form fields in a form matters when retrieving FormData from a form element. Disabled fields will not be included for example. Make sure to handle this before using the data.
On Internet Explorers, this function needs a polyfill, which is not included in annex, due to its size and complexity, since IEs, while supporting FormData basically, are lacking all functions to access values of an existing FormData object, thereby making it impossible to iterate its values.
Parameters:
Name | Type | Description |
---|---|---|
formDataOrForm |
FormData | HTMLFormElement | either an existing FormData object or a form, from which we can retrieve formdata |
- Source:
- See:
Returns:
- Type
- Object
Example
const formData = new FormData();
formData.append('secrethash', 123456789);
formData.append('firstname', 'Paul');
formData.append('lastname', 'Atreides');
formData.append('houses', 'Atreides');
formData.append('houses', 'Fremen');
formData.append('houses', 'Corrino');
formData.append('diary', new File(['Dear Diary, ...'], 'diary.txt', {type : 'text/plain', lastModified : new Date()}));
formData.append('instagramPage', new Blob(['<html>...</html>'], {type : 'text/html'}));
formDataToObject(formData)
=>
{
secrethash : '123456789',
firstname : 'Paul',
lastname : 'Atreides',
houses : ['Atreides', 'Fremen', 'Corrino'],
diary : File,
instagramPage : Blob
}