Skip to content

Instantly share code, notes, and snippets.

@akrawchyk
Last active August 29, 2015 14:00
Show Gist options
  • Save akrawchyk/11179336 to your computer and use it in GitHub Desktop.
Save akrawchyk/11179336 to your computer and use it in GitHub Desktop.
Serialize input to JSON
/**
* Creates JSON for a single input field
*
* e.g. article[id] = 1 => { article: {id: 1}}
*
* @param {Node} inputElem - :input element to serialize
* @returns {object}
*/
var serializeInputToJSON = function(inputElem) {
var name = inputElem.name;
var rootName = inputElem.name.split('[')[0]; // param before nesteds
var value = inputElem.value;
var root = {};
var nestedParamRegex = /\[(\w*)\]/g;
var nestedParams = name.match(nestedParamRegex);
/**
* Recursively traverses input name to build JSON from
* the deepest param out, excluding the root
*
* e.g. article[id]=1 -> {id: 1}
*
* @param {object} obj - object to wrap params around
* @param {array} params - array of params matched from nestedParamRegex
*/
function addNestedParam(obj, params) {
if (!params.length) {
return obj;
}
var copy = {};
var param = params.pop();
var arrayParam;
if (Object.keys(obj).length === 0) {
// deepest point, assign value of input
if (param === '[]') {
// multiple select
arrayParam = params.pop().slice(1, -1);
if (inputElem.multiple) {
copy[arrayParam] = getMultipleValues(inputElem);
}
} else {
copy[param.slice(1, -1)] = value;
}
} else {
if (param === '[]') {
// array belongs to parent param
arrayParam = params.pop().slice(1, -1);
copy[arrayParam] = [obj];
} else {
// wrap new param around previous data
param = param.slice(1, -1);
copy[param] = obj;
}
}
return addNestedParam(copy, params);
}
function getMultipleValues(selectElem) {
var selected = selectElem.selectedOptions;
var i = 0, l = selected.length;
var retArray = [];
for (; i < l; i++) {
if (selected[i].value) {
retArray.push(selected[i].value);
}
}
return retArray;
}
if (nestedParams) {
root[rootName] = addNestedParam({}, nestedParams);
} else {
root[rootName] = value;
}
return root;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment