JSFiddle - React, Tailwind, and code Playground
HTML
<form id="sample">
<input name="name" type="text" value="name value" />
<input name="phone[0][type]" type="text" value="cell" />
<input name="phone[0][number]" type="text" value="000" />
<input name="phone[1][type]" type="text" value="home" />
<input name="phone[1][number]" type="text" value="111" />
</form>
JavaScript
$(document).ready(function () {
// This is the JSON object that will hold the result:
var serialized = {};
var currentName;
var lastIndex = -1;
// Loops each input field inside #sample form.
$('#sample input').each(function () {
// Recover the input Name attribute.
var inputName = $(this).attr('name');
if (inputName.indexOf('[') == -1) {
// When input name doens't have "[]", just serialize its value.
eval('serialized.' + inputName + ' = "' + $(this).val() + '"');
} else {
// When "[]" exists, recover the main name, before the first "[".
var mainName = inputName.substring(0, inputName.indexOf("["));
// The variables "currentName" and "lastIndex" controls the nodes being used.
if (mainName != currentName) {
currentName = mainName;
lastIndex = -1;
}
// Create the main array if undefined.
if (eval('serialized.' + mainName) == undefined) {
eval('serialized.' + mainName + ' = []');
}
// Recover the current element index.
var newIndex = parseInt(inputName.substring(inputName.indexOf("[") + 1, inputName.indexOf("]")));
// Check if the index changed since the last element checked.
if (lastIndex != newIndex) {
lastIndex = newIndex;
// If is a new index, create a neu object inside this index.
eval('serialized.' + mainName + '[' + newIndex + '] = {}');
}
// Put the child property name (i.e., "type" or "number") inside the object of that index.
var childName = inputName.substring(inputName.lastIndexOf("[") + 1, inputName.lastIndexOf("]"));
eval('serialized.' + mainName + '[' + newIndex + '].' + childName + ' = "' + $(this).val() + '"');
}
});
// With the structure created, you can use the...