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

如何将serialisedArray得到的JS数组合并为目标数组?

嘿,我来帮你解决这个序列化数组转换的问题!你拿到的是serializeArray()返回的典型结构,要把它转换成更整洁的结构化数组其实很简单,下面给你两种实用的实现方式:

方法1:原生JavaScript reduce 方法(推荐)

这是最灵活且不依赖额外库的方案,哪怕你有多个sub_maintenance_template[n]条目,它也能自动对应到数组的正确位置:

// 你的原始序列化数组
const serializedData = [
  { name: "sub_maintenance_template[1][maintenance_location_id]", value: "54321" },
  { name: "sub_maintenance_template[1][maintenance_problem_id]", value: "65432" },
  { name: "sub_maintenance_template[1][maintenance_priority_id]", value: "76896" },
  { name: "sub_maintenance_template[1][description]", value: "sample description" }
];

// 转换逻辑
const transformedArray = serializedData.reduce((acc, current) => {
  // 用正则提取索引和属性名
  const matchResult = current.name.match(/sub_maintenance_template\[(\d+)\]\[(\w+)\]/);
  
  if (matchResult) {
    // 提取索引(这里把1-based转成0-based数组索引,不需要的话直接用parseInt(matchResult[1]))
    const itemIndex = parseInt(matchResult[1]) - 1;
    const propertyName = matchResult[2];
    
    // 确保当前索引的对象已初始化
    if (!acc[itemIndex]) {
      acc[itemIndex] = {};
    }
    
    // 赋值,顺便处理数字类型转换(可选)
    acc[itemIndex][propertyName] = !isNaN(current.value) ? Number(current.value) : current.value;
  }
  
  return acc;
}, []);

console.log(transformedArray);

输出结果:

[
  {
    maintenance_location_id: 54321,
    maintenance_problem_id: 65432,
    maintenance_priority_id: 76896,
    description: "sample description"
  }
]

方法2:jQuery辅助转换(如果已使用jQuery)

如果你的项目已经依赖jQuery,可以通过URL参数转JSON的方式快速实现,适合单一条目的场景:

const serializedData = [/* 你的原始数组 */];

// 转成URL参数字符串
const paramString = $.param(serializedData);
// 替换格式为JSON兼容的结构
const jsonString = `{"${paramString.replace(/&/g, '","').replace(/=/g, '":"').replace(/sub_maintenance_template\[1\]\[(\w+)\]/g, '$1')}"}`;
const transformedObj = JSON.parse(jsonString);

// 如果你需要数组格式,把它包进数组即可
const transformedArray = [transformedObj];
console.log(transformedArray);

小提示

  • 如果你的表单有多个sub_maintenance_template[n](比如[2]、[3]),方法1会自动把它们分到数组的对应位置,扩展性更强。
  • 数字类型转换是可选的,如果不需要保留数字类型,直接赋值current.value即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:27:38