Created
April 19, 2016 21:26
-
-
Save zeroasterisk/b92b3d75680db2f1e5776406393bd8f8 to your computer and use it in GitHub Desktop.
React friendly utility to get a data object from a form onSubmit event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* TEMP WIP Form helper utilities | |
* | |
*/ | |
import _ from 'lodash'; | |
export function getOptions(options) { | |
return _.extend( | |
{ | |
fields: [], | |
omitFields: [] | |
}, | |
options || {} | |
); | |
} | |
export function getDataFromEvent(event, options) { | |
options = getOptions(options); | |
event.preventDefault(); | |
return getDataFromElements(event.target.elements, options); | |
} | |
export function filterElements(elements, options) { | |
return _.filter(elements, filterElement.bind(this, options)); | |
} | |
export function filterElement(options, el) { | |
if (options.fields.length > 0) { | |
if (_.indexOf(options.fields, el.name) === -1) { | |
return false; | |
} | |
} | |
if (options.omitFields.length > 0) { | |
if (_.indexOf(options.omitFields, el.name) !== -1) { | |
return false; | |
} | |
} | |
return true; | |
} | |
export function getDataFromElements(elements, options) { | |
options = getOptions(options); | |
return _.fromPairs( | |
_.map( | |
filterElements(elements, options), | |
(el) => { return [el.name, el.value]; } | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment