Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Transform formData from a form element into Object literal.
/**
* `objFromFlatKeys` Convert the template string into a tree path and set the value into the referenced object path.
*
* @param {string} strPath - template string path to convert in nested object tree
* @param {Object} prevobj - reference for the nested object result
* @param {*} value - value to set at the end of the nested object tree
*
* @example
* // define the target object
* const obj = {};
* // multiple call
* objFromFlatKeys('root.item[]', obj, 'A');
* objFromFlatKeys('root.item[]', obj, 'B');
* console.log(obj);
* // logs: { root: { item: { 0: 'A', 1: 'B' } } }
*
* @author João Neto <joaopintoneto@gmail.com>
* @license MIT
*/
function objFromFlatKeys(strPath, prevobj, value) {
const tokens = strPath
.replace(/\[(.*?)\]/g, ".$1")
.replace(/\.+/g, ".")
.split(".");
const lastTokenIndex = tokens.length - 1;
tokens.forEach((key, i) => {
let k = key || Object.keys(prevobj).length;
prevobj[k] = i === lastTokenIndex ? value : prevobj[k] || {};
prevobj = prevobj[k];
});
}
/**
* `formDataToObject` Transform formData from a form element into Object literal.
*
* @param {HTMLElement} formElement
* @returns Object
*
* @example
* // given the follow html
* <form id="form">
* <input type="text" name="root.item[]" />
* <input type="text" name="root.item[]" />
* <button type="submit">submit</button>
* </form>
*
* // when form is submitted
* document.getElementById("form")
* .addEventListener("submit", function (e) {
* e.preventDefault();
* console.log(formDataToObject(this))
* // logs: { root: { item: { 0: 'A', 1: 'B' } } }
* });
*
* @author João Neto <joaopintoneto@gmail.com>
* @license MIT
*/
function formDataToObject(formElement) {
const formData = new FormData(formElement);
const obj = {};
[...formData.entries()].forEach(([key, value]) => {
objFromFlatKeys(key, obj, value || "");
});
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment