Files
Reservair/assets/js/forms/RsvFormEncoder.js
T

42 lines
1.3 KiB
JavaScript
Raw Normal View History

2026-06-12 10:57:23 +00:00
export const RsvFormEncoder = {
2026-06-11 19:03:29 +02:00
// Serialize form element into a plain JS object supporting arrays.
// - Nested keys supported with dot notation: 'meta.email'
// - Array notation supported with trailing [] (e.g. 'times[]') or multiple inputs with same name
encode_form(form_element) {
const formData = new FormData(form_element);
const body = {};
for (const [rawKey, value] of formData.entries()) {
const isArrayNotation = rawKey.endsWith('[]');
const key = isArrayNotation ? rawKey.slice(0, -2) : rawKey;
const keys = key.split('.');
let current = body;
for (let i = 0; i < keys.length - 1; i++) {
const k = keys[i];
if (current[k] === undefined || typeof current[k] !== 'object') {
current[k] = {};
}
current = current[k];
}
const lastKey = keys[keys.length - 1];
if (isArrayNotation) {
if (!Array.isArray(current[lastKey])) current[lastKey] = [];
current[lastKey].push(value);
} else {
if (current[lastKey] === undefined) {
current[lastKey] = value;
} else if (Array.isArray(current[lastKey])) {
current[lastKey].push(value);
} else {
current[lastKey] = [current[lastKey], value];
}
}
}
return body;
}
}