Задача немного сложнее, чем идея, которую вы представили. При создании ветвей из «свойств» в именах элементов формы вам понадобится рекурсивная функция, которая будет следовать «пути» до того, как будет установлено значение последнего свойства. Как то так:
function form2Obj(form) {
if (Object.prototype.toString.apply(form) !== '[object HTMLFormElement]') {
return;
}
const obj = Object.create(null); // The return value
const inputs = Array.from(form.elements);
// Creates new properties and values to the return value object
const addProp = (target, name, element) => {
const branches = name.split('.');
// Extract the current name to handle
const current = branches.shift();
if (branches.length) {
// Not the last part of the name
if (!(current in target)) {
// The property doens't exist, create it
target[current] = {};
}
// Evaluate the next part of the name
addProp(target[current], branches.join('.'), element);
} else {
// This is the last part of the name, get the value from the element
target[current] = element.value;
}
};
inputs.forEach(input => {
addProp(obj, input.name, input);
});
return obj;
}
console.log(form2Obj(document.querySelector('#foo-bar-baz-form')));
<form id="foo-bar-baz-form">
<input name="bar.baz" value="">
<input name="baz" value="">
<input name="foo.bar.baz" value="">
</form>
Обратите внимание, что form2Obj
возвращает объект, вам еще предстоит преобразовать его в JSON, если JSON действительно необходим. Вот скрипка для тестирования.