如何在循环中生成带序号键的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
相关产品推荐
相关产品推荐

