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

如何通过POST请求给对象新增嵌套对象数组,数组存在则直接追加元素

实现方案

整体逻辑为前端传递要修改的问题ID和新增回答内容,后端负责读取存储的问题数据、判断answers数组是否存在、追加内容后回写存储即可。

1. 前端请求示例

Axios 版本

// 封装新增回答请求
async function addAnswer(questionId, newAnswer) {
  try {
    const response = await axios.post('/api/add-answer', {
      questionId: questionId,
      newAnswer: newAnswer
    })
    console.log('回答添加成功', response.data)
  } catch (error) {
    console.error('回答添加失败', error)
  }
}

// 调用示例
addAnswer('2', {
  answerBrief: "Check under the bed",
  answerCode: "no code sorry",
  answerAuthor: "Sonya"
})

Fetch 版本

async function addAnswer(questionId, newAnswer) {
  try {
    const response = await fetch('/api/add-answer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        questionId: questionId,
        newAnswer: newAnswer
      })
    })
    const result = await response.json()
    console.log('回答添加成功', result)
  } catch (error) {
    console.error('回答添加失败', error)
  }
}

2. 后端处理逻辑(Node.js 示例)

核心的数组判断、追加逻辑都在后端实现,以下是操作本地questions.json文件的示例代码:

const fs = require('fs/promises')
const path = require('path')
// 你的questions.json文件本地路径
const QUESTION_FILE_PATH = path.join(__dirname, './questions.json')

async function addAnswerHandler(req, res) {
  const { questionId, newAnswer } = req.body
  try {
    // 读取json文件内容
    const fileData = await fs.readFile(QUESTION_FILE_PATH, 'utf-8')
    const questionList = JSON.parse(fileData)

    // 找到对应ID的目标问题
    const targetQuestion = questionList.find(item => item.id === questionId)
    if (!targetQuestion) {
      return res.status(404).json({ code: 404, msg: '未找到对应问题' })
    }

    // 判断answers数组是否存在,不存在则初始化
    if (!Array.isArray(targetQuestion.answers)) {
      targetQuestion.answers = []
    }

    // 追加新回答
    targetQuestion.answers.push(newAnswer)

    // 回写修改后的数据到json文件
    await fs.writeFile(QUESTION_FILE_PATH, JSON.stringify(questionList, null, 2))

    return res.json({ code: 200, msg: '添加成功', data: targetQuestion })
  } catch (err) {
    console.error('处理出错', err)
    return res.status(500).json({ code: 500, msg: '服务器内部错误' })
  }
}

注意:生产环境建议用数据库存储数据而非直接操作JSON文件,避免并发写入导致的文件损坏。如果使用其他后端语言(Go/Java/Python等),处理逻辑完全一致:读取存储的问题数据→判断answers字段是否存在→不存在则初始化为空数组→追加新回答→回写存储即可。

内容的提问来源于stack exchange,提问作者krishna-chavan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:36:05