如何按ID选团队、按姓名选成员,向其planning数组添加JSON对象?
需求与解决方案
我需要向JSON文件中添加一个对象,但需先通过ID选择对应的servX团队,再通过姓名选择成员,将元素添加到该成员的planning数组中。团队ID和成员姓名为变量。
现有JSON文件内容
[ { "name": "serv1", "id": "1", "members": [ { "id": "1", "name": "Michel", "planning": [ { "id": "26/07/2022", "type": "TT" }, { "id": "16/08/2022", "type": "TT" } ] }, { "id": "2", "name": "Paul", "planning": [ { "id": "25/07/2022", "type": "TT" }, { "id": "28/07/2022", "type": "TT" } ] } ] }, { "name": "serv2", "id": "2", "members": [ { "id": "1", "name": "Michel", "planning": [ { "id": "16/07/2022", "type": "TT" } ] }, { "id": "2", "name": "Paul", "planning": [ { "id": "18/07/2022", "type": "TT" } ] } ] } ]
现有Server.js代码片段
app.get("/add", (req, res) => { let id = req.query.id; id = id.substr(0, 10); let type = req.query.type; let team = req.query.team; let name = req.query.name; if (type == "orange") { type = "none"; } else if (type == "green") { type = "TT"; } let toPush = { id: id, type: type, }; (team = parseFloat(team)), (team -= 1); fs.readFile(__dirname + "/public/services.json", (err, data) => { if (err) throw err; let json = JSON.parse(data); }); });
修改后的完整代码实现
const fs = require('fs'); // 假设app已通过express初始化完成 app.get("/add", (req, res) => { let id = req.query.id; id = id.substr(0, 10); let type = req.query.type; const teamId = req.query.team; // 直接用传入的团队ID字符串匹配,避免索引匹配出错 const memberName = req.query.name; // 转换type对应值 if (type === "orange") { type = "none"; } else if (type === "green") { type = "TT"; } const toPush = { id: id, type: type, }; fs.readFile(__dirname + "/public/services.json", (err, data) => { if (err) { console.error(err); return res.status(500).send('读取文件失败'); } let json = JSON.parse(data); // 1. 通过团队ID定位目标团队 const targetTeam = json.find(team => team.id === teamId); if (!targetTeam) { return res.status(404).send('未找到指定团队'); } // 2. 通过成员姓名定位目标成员 const targetMember = targetTeam.members.find(member => member.name === memberName); if (!targetMember) { return res.status(404).send('未找到指定成员'); } // 3. 将新对象添加到成员的planning数组 targetMember.planning.push(toPush); // 4. 将修改后的JSON写回文件 fs.writeFile(__dirname + "/public/services.json", JSON.stringify(json, null, 2), (writeErr) => { if (writeErr) { console.error(writeErr); return res.status(500).send('写入文件失败'); } res.status(200).send('规划已成功添加'); }); }); });
关键修改说明
- 放弃数组索引匹配团队的方式,改用
find方法根据团队ID精确匹配,避免团队顺序变化导致的错误 - 新增完整错误处理:文件读写失败、团队/成员未找到时返回对应状态码和提示
- 补全从定位目标到写入修改后文件的完整流程
- 使用
JSON.stringify(json, null, 2)保证写入的JSON格式美观易读
内容的提问来源于stack exchange,提问作者Magic Addict
相关产品推荐
相关产品推荐

