formToJSON_deconstructed
Mon Oct 10 2022 10:04:38 GMT+0000 (Coordinated Universal Time)
Saved by
@Wchoi189
#javascript
const formToJSON_deconstructed = (elements) => {
// This is the function that is called on each element of the array.
const reducerFunction = (data, element) => {
// Add the current field to the object.
data[element.name] = element.value;
// For the demo only: show each step in the reducer’s progress.
console.log(JSON.stringify(data));
return data;
};
// This is used as the initial value of `data` in `reducerFunction()`.
const reducerInitialValue = {};
// To help visualize what happens, log the inital value.
console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));
// Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
const formData = [].reduce.call(
elements,
reducerFunction,
reducerInitialValue,
);
// The result is then returned for use elsewhere.
return formData;
};
content_copyCOPY
https://www.learnwithjason.dev/blog/get-form-values-as-json
Comments