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

如何递归将FormData转换为JSON并完整保留层级结构?

我知道本站此前已有相关提问,但均未覆盖这一特定问题。

当我们拥有如下表单时:

<input name="A" .. />
<input name="B[x1]" .. />
<input name="C[y][z]".. />

目前已有的公开方案都只会生成扁平层级的JSON,例如:

{
   "A" : "1",
   "B[x1]" : "2" 
}

但我们实际需要生成的正确FormData转换结果应为嵌套结构,如下所示:

{
   "A" : "1",
   "B" : {
      "x1":"2"
   }
}

请问是否存在标准的JS内置方法可以实现该需求?

解答

目前不存在JS内置的标准方法可以直接实现该需求,你可以使用自定义函数完成转换,示例代码如下:

function formDataToNestedJson(formData) {
  const nestedObj = {};
  // 遍历FormData所有键值对
  for (const [fieldName, fieldValue] of formData.entries()) {
    // 拆分字段名的层级,例如 C[y][z] 拆分为 ['C', 'y', 'z']
    const keyPath = fieldName.match(/[^\[\]]+/g);
    let currentLayer = nestedObj;
    // 逐层构建嵌套对象
    for (let i = 0; i < keyPath.length; i++) {
      const currentKey = keyPath[i];
      // 最后一层直接赋值
      if (i === keyPath.length - 1) {
        currentLayer[currentKey] = fieldValue;
        continue;
      }
      // 非最后一层若不存在对应属性,初始化为空对象
      if (!currentLayer[currentKey]) {
        currentLayer[currentKey] = {};
      }
      currentLayer = currentLayer[currentKey];
    }
  }
  return nestedObj;
}

调用示例:

// 获取页面表单实例
const targetForm = document.querySelector('form');
// 生成FormData对象
const formData = new FormData(targetForm);
// 转换为嵌套结构对象
const result = formDataToNestedJson(formData);
// 打印JSON格式结果
console.log(JSON.stringify(result, null, 2));

以上代码支持任意层级的嵌套字段命名转换,可覆盖你提出的使用场景。


内容的提问来源于stack exchange,提问作者T.Todua

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:36:02