diff --git a/snippets/formToObject.md b/snippets/formToObject.md new file mode 100644 index 000000000..a05a3ae72 --- /dev/null +++ b/snippets/formToObject.md @@ -0,0 +1,25 @@ +### formToObject + +Serializes a form into an object. + +First we transform the `form` into `FormData`, then we convert it into an `array` and from the `array` we collect an `object` + +```js +const formToObject = form => + Array.from(new FormData(form)) + .reduce((acc, [key, value]) => ({ + ...acc, + [key]: value, + }), {}) +``` + +```html +
+ + +
+``` + +```js +formToObject(document.querySelector('#form')) // { email: 'test@email.com', name: 'Test Name' } +``` \ No newline at end of file diff --git a/snippets/serializeForm.md b/snippets/serializeForm.md index 4553ff858..35bf865f2 100644 --- a/snippets/serializeForm.md +++ b/snippets/serializeForm.md @@ -2,15 +2,11 @@ Serializes a form into an object. -First we transform the `form` into `FormData`, then we convert it into an `array` and from the `array` we collect an `object` +First we transform the `form` into `FormData`, then we convert it into an `array` and from the `array` we collect an `query string` ```js const serializeForm = form => - Array.from(new FormData(form)) - .reduce((acc, [key, value]) => ({ - ...acc, - [key]: value, - }), {}) + Array.from(new FormData(form), field => field.map(encodeURIComponent).join('=')).join('&') ``` ```html @@ -21,5 +17,5 @@ const serializeForm = form => ``` ```js -serializeForm(document.querySelector('#form')) // { email: 'test@email.com', name: 'Test Name' } +serializeForm(document.querySelector('#form')) // email=test%40email.com&name=Test%20Name ``` \ No newline at end of file diff --git a/tag_database b/tag_database index 109dbd265..b86472c19 100644 --- a/tag_database +++ b/tag_database @@ -90,6 +90,7 @@ flattenObject:object,recursion,intermediate flip:adapter,function,intermediate forEachRight:array,function,intermediate formatDuration:date,math,string,utility,intermediate +formToObject:browser,utility,object forOwn:object,intermediate forOwnRight:object,intermediate fromCamelCase:string,intermediate @@ -264,7 +265,7 @@ sampleSize:array,random,intermediate scrollToTop:browser,intermediate sdbm:math,utility,intermediate serializeCookie:utility,string,intermediate -serializeForm:browser,beginner,utility +serializeForm:browser,beginner,utility,string setStyle:browser,beginner shallowClone:object,beginner shank:array,intermediate