You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将jQuery serializeArray()返回的键值对数组转换为按记录分组的对象数组

实现方案

你可以通过遍历serializeArray()返回的扁平数组,按recid为标识拼接结构化对象,实现代码如下:

// 这里的data就是你调用serializeArray得到的原始数据
const data = table.$('input,select,textarea').serializeArray();

const result = []
let currentRecord = null

data.forEach(field => {
  if (field.name === 'recid') {
    // 遇到recid时初始化新的记录对象
    currentRecord = {
      recid: Number(field.value),
      notes: null
    }
    result.push(currentRecord)
  } else if (field.name === 'notes' && currentRecord) {
    // 空字符串转换为null,非空则保留原值
    currentRecord.notes = field.value.trim() === '' ? null : field.value
  }
})

// 转换完成的result就是目标格式数据
console.log(JSON.stringify(result, null, 2))

如果后续表单需要新增其他字段,只需要对应增加else if分支处理对应字段的赋值逻辑即可。


内容的提问来源于stack exchange,提问作者sdelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 13:48:02