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

如何将FormData生成的结构化对象转换为JavaScript数组?

问题:将FormData转换的扁平对象转为嵌套数组结构

请问在JavaScript中是否存在方法,可将从FormData转换而来的如下结构化对象:

{ 
 Control[0].Eseguito: "true",
 Control[0].Id:"2",
 Control[0].Nota:"",
 Control[1].Eseguito: "true",
 Control[1].Id:"2",
 Control[1].Nota:""
}

转换为如下格式的JavaScript数组?

{
  Control: [
    {Id: '2', Eseguito: "true", Nota: ''},
    {Id: '2', Eseguito: "true", Nota: ''}
  ]
}

补充说明:我通过以下代码将表单FormData转换为对象:

let myForm = document.getElementById('ControlForm');
var Controls = Object.fromEntries(new FormData(myForm).entries());

我的ExecControl.cshtml文件中有如下代码片段(仅展示部分内容):

@{ 
    int Indice = 0;
}

@for (int i = 0; i < Model.ListControls.Length; i++)
{
    for (int j = 0; j < Model.ListControls[i].Controls.Length; j++)
    {
        ...
        <input type="text" style="width:100%;" name="Control[@Indice].Nota"/>
        <input type="text" style="width:100%;" name="Control[@Indice].Id" value="@Model.ListControls[i].Controls[j].Id"/>
        ...
    }
}

解决方案

你可以自行实现解析函数,遍历扁平对象的键名,提取数组索引和属性字段,再构建目标嵌套结构:

function transformFlatControls(flatObj) {
  const result = { Control: [] };
  
  for (const key in flatObj) {
    // 匹配 Control[索引].属性名 的格式
    const match = key.match(/Control\[(\d+)\]\.(\w+)/);
    if (match) {
      const index = parseInt(match[1]);
      const prop = match[2];
      const value = flatObj[key];
      
      // 初始化对应索引的对象(如果不存在)
      if (!result.Control[index]) {
        result.Control[index] = {};
      }
      // 为对象赋值属性
      result.Control[index][prop] = value;
    }
  }
  
  return result;
}

// 使用示例
let myForm = document.getElementById('ControlForm');
var flatControls = Object.fromEntries(new FormData(myForm).entries());
var structuredControls = transformFlatControls(flatControls);
console.log(structuredControls.Control);

额外注意事项

  1. 正则表达式/Control\[(\d+)\]\.(\w+)/用于精准提取键名中的数组索引和属性字段,适配你当前的表单命名规则。
  2. 你的cshtml代码中,Indice变量需要在每次内层循环末尾添加Indice++;,否则所有输入框会共用同一个索引值,导致转换后的数据出现覆盖异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:25:18