I've got an HTML form that consists of a series of units like this:
<input name="categoryColor[]" />
<input name="categoryName[]" />
Using this jQuery code, I can capture this data and return it in an object like this:
{categoryColor: [array of values],
categoryName: [array of values]}
Here's an example of the code in action:
const getFormDataFromElem = function($elem, options) {
options = options || {};
const vis = options.onlyVisible ? ":visible" : "";
const formInputs = $elem.find(`:input${vis}, [contenteditable=true]${vis}`);
const data = {};
formInputs.each(function() {
const $this = $(this)
const type = $this.attr('type');
const val = type === "checkbox" ? (this.checked ? "1" : "0") :
($this.is('[contenteditable=true]') ? $this.text() : this.value);
const name0 = $this.attr('name');
const doArray = name0 && name0.slice(-2) === "[]";
const name = doArray ? name0.slice(0, -2) : name0;
if (!name || (!options.saveEmpty && !doArray && val === "")) {
return;
}
if (doArray) {
if (data.hasOwnProperty(name)) {
data[name].push(val);
return
}
data[name] = [val];
return;
}
data[name] = val;
});
return data;
};
const data = getFormDataFromElem($('.input'));
$('.output').text(JSON.stringify(data, null, 2));
.output {
font-family: monospace;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Input</h2>
<div class="input">
<input name="categoryName[]" value="phase1"/>
<input name="categoryColor[]" value="red"/>
<input name="categoryName[]" value="phase2"/>
<input name="categoryColor[]" value="green"/>
<input name="categoryName[]" value="phase3"/>
<input name="categoryColor[]" value="blue"/>
</div>
<h2>Output</h2>
<div class="output"></div>
BUT I'd like to be able to write the HTML form units like this
<input name="categories[].color" />
<input name="categories[].name" />
since I really need this data in this form:
{categories: [array of objects],
}
where the objects have the form {name: '<name of category>', color: '<color string>'}
.
How would I rewrite my general-purpose form-capturing routine to produce values that are arbitrary arrays and objects?