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

如何将含数组索引的对象解析为键值对形式的对象数组

技术方案:扁平字段对象转嵌套数组结构

需求说明

输入为包含SubmitBy字段及带数组索引的Students[X].name/Students[X].age格式字段的扁平对象,需要转换为包含SubmitBy字段和Students数组的结构,数组每个元素是包含name与age属性的对象。

输入示例:

{
  "SubmitBy":"SK",
  "Students[0].name":"Jhon",
  "Students[0].age":"15",
  "Students[1].name":"Sam",
  "Students[1].age":"16",
  "Students[2].name":"Tom",
  "Students[2].age":15
}

期望输出示例:

{
  "SubmitBy":"SK",
  "Students":[
    {"name":"Jhon", "age":"15"},
    {"name":"Sam", "age":"16"},
    {"name":"Tom", "age":15}
  ]
}

实现思路

  1. 初始化输出对象,直接保留输入中的SubmitBy字段,同时创建空的Students数组
  2. 遍历输入对象的所有键值对,筛选出Students[*]开头的字段
  3. 通过正则解析字段名中的数组索引和属性名,将对应值存入Students数组的对应位置对象中
  4. 自动处理索引顺序,确保数组元素与输入的索引对应

代码实现(JavaScript)

function transformStudentData(input) {
  const output = {
    SubmitBy: input.SubmitBy,
    Students: []
  };

  for (const [key, value] of Object.entries(input)) {
    if (key === 'SubmitBy') continue;

    // 匹配Students[索引].属性的格式
    const keyMatch = key.match(/^Students\[(\d+)\]\.(name|age)$/);
    if (keyMatch) {
      const idx = parseInt(keyMatch[1], 10);
      const prop = keyMatch[2];

      // 若该索引位置无对象则初始化
      if (!output.Students[idx]) {
        output.Students[idx] = {};
      }
      output.Students[idx][prop] = value;
    }
  }

  return output;
}

// 测试用例
const inputData = {
  "SubmitBy":"SK",
  "Students[0].name":"Jhon",
  "Students[0].age":"15",
  "Students[1].name":"Sam",
  "Students[1].age":"16",
  "Students[2].name":"Tom",
  "Students[2].age":15
};

console.log(transformStudentData(inputData));

关键说明

  • 正则表达式/^Students\[(\d+)\]\.(name|age)$/精准匹配目标字段,避免处理无关键值对
  • 保留原始值的类型(如示例中Tom的age为数字类型,输出时不会被转换为字符串)
  • 即使输入的字段顺序混乱,也能通过索引正确映射到数组的对应位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:10:23