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

JavaScript中如何将serializeArray结果转换为多对象结构?

将表单序列化结果转换为分组对象集合

你通过jQuery('.sts_create form').serializeArray()获取的表单序列化数组中,存在重复字段名的条目,需要按target_tag字段分组,每个分组对应一个包含target_tag、animation_status、duration三个属性的对象,最终生成以索引为键的对象集合。

实现代码

const serialized = jQuery('.sts_create form').serializeArray();
const result = {};
let currentIndex = 0;
let currentObj = {
  target_tag: '',
  animation_status: '',
  duration: ''
};

serialized.forEach(item => {
  if (item.name === 'target_tag') {
    // 若已有正在构建的对象,先存入结果集
    if (currentIndex > 0 || currentObj.target_tag !== '') {
      result[currentIndex] = {...currentObj};
      currentIndex++;
    }
    // 初始化新的分组对象
    currentObj = {
      target_tag: item.value,
      animation_status: '',
      duration: ''
    };
  } else {
    // 为当前分组对象赋值对应属性
    if (currentObj.hasOwnProperty(item.name)) {
      currentObj[item.name] = item.value;
    }
  }
});

// 存入最后一个分组对象
if (currentObj.target_tag !== '' || currentObj.animation_status !== '' || currentObj.duration !== '') {
  result[currentIndex] = currentObj;
}

console.log(result);

代码逻辑说明

  1. 初始化变量:result存储最终结果,currentIndex记录当前分组的索引,currentObj临时存储正在构建的单个分组对象,预设三个属性为空值。
  2. 遍历序列化数组:
    • 遇到target_tag字段时,先将已构建完成的currentObj存入result(避免第一个分组重复存入),再初始化新的currentObj并设置target_tag的值。
    • 遇到其他字段时,直接为currentObj的对应属性赋值,通过hasOwnProperty确保只处理预设的三个属性。
  3. 收尾处理:遍历结束后,将最后一个未存入的分组对象添加到result中,避免遗漏。

测试结果

针对你提供的输入:

[
  {name: 'target_tag', value: 'a'},
  {name: 'animation_status', value: 'animation-1'},
  {name: 'duration', value: ''},
  {name: 'target_tag', value: 'div'}
]

运行代码后得到的result结构如下:

{
  0: {
    target_tag: 'a',
    animation_status: 'animation-1',
    duration: ''
  },
  1: {
    target_tag: 'div',
    animation_status: '',
    duration: ''
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:07:25