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

如何在循环中生成带序号键的JSON数据结构?

问题与解决方案

原代码与当前输出

原JavaScript代码:

let paragraph_json = [];

for (let paragraph = 1; paragraph <= 3; paragraph++) {
  paragraph_json.push({
    text: `this is paragraph ${paragraph}`,
  });
}

res.json({
  data: paragraph_json,
});

当前输出JSON:

{
    "data": [
      {
        "text": "this is paragraph 1"
      }, 
      {
        "text": "this is paragraph 2"
      }, 
      {
        "text": "this is paragraph 3"
      }
    ]
}

需求说明

需要生成带段落序号作为键的JSON结构,注意你期望的格式中data应为对象而非数组(JSON数组不支持键值对形式的元素),目标格式如下:

{
    "data": {
      "1": {
        "text": "this is paragraph 1"
      }, 
      "2": {
        "text": "this is paragraph 2"
      }, 
      "3": {
        "text": "this is paragraph 3"
      }
    }
}

修改后的代码

把paragraph_json从数组换成对象,循环内直接给对象添加对应序号的键值对:

let paragraph_json = {}; // 将数组替换为对象

for (let paragraph = 1; paragraph <= 3; paragraph++) {
  // 用段落序号作为对象键,赋值对应的段落对象
  paragraph_json[paragraph] = {
    text: `this is paragraph ${paragraph}`,
  };
}

res.json({
  data: paragraph_json,
});

最终输出结果

运行修改后的代码,会生成符合需求的JSON:

{
    "data": {
      "1": {
        "text": "this is paragraph 1"
      }, 
      "2": {
        "text": "this is paragraph 2"
      }, 
      "3": {
        "text": "this is paragraph 3"
      }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:13:27