如何将jQuery序列化的表单数据转换为指定结构的JSON数组
具体实现方案
核心思路是对jQuery serializeArray() 返回的扁平化键值对,通过正则解析带数组索引的嵌套键名,按索引分组聚合出目标数组结构,无需依赖第三方工具库。
可直接使用的转换代码
const parseFormToNested = (serializeRes) => { const result = {}; serializeRes.forEach(({ name, value }) => { // 匹配 itinerary[0][date] 这类带嵌套索引的键名 const reg = /^(\w+)\[(\d+)\]\[(\w+)\]$/; const match = name.match(reg); if (!match) return; const [, rootKey, index, field] = match; // 初始化目标结构容器 if (!result[rootKey]) result[rootKey] = []; if (!result[rootKey][index]) result[rootKey][index] = {}; // 过滤掉值为undefined、空字符串的无效字段 if (value === undefined || value === '') return; result[rootKey][index][field] = value; }) return result; } // 实际调用 const rawData = $("#formitinerary").serializeArray(); const structuredData = parseFormToNested(rawData); // structuredData.itinerary 即为符合要求的对象数组结构
效果说明
- 针对你当前的测试数据,处理后会自动过滤值为
undefined的date字段,最终得到的itinerary结构为:
itinerary: [ { title: 'Day 1 to Colombo', destinationId: '5ff3b8d7f0f3bf04b8141362', program: 'asd', transfer_duration: '2 hours' } ]
- 只要表单字段命名遵循
父级键名[数组索引][字段名]的规则,无需修改代码即可自动识别分组,不需要硬编码itinerary的路径 - 如果后续存在更深层级的嵌套字段,仅需扩展正则匹配规则,增加递归赋值逻辑即可适配
内容的提问来源于stack exchange,提问作者thatrafi
相关产品推荐
相关产品推荐

