繁体   English   中英

如何向对象添加新的对象数组以使其嵌套,如果新添加的数组已存在,则向该数组添加另一个对象?

[英]How to add a new array of objects to an object to make it nested and if newly added array already exists, add another object to that array?

我有一组对象questions.json看起来像

   "id": "2",
  "ques": "here is my second code ?",
  "quesBrief": "I can't seem to find it too.",
  "hashes": "#javascript , #goodlord",
  "author": "slowdeathv123",
  "dateTime": "2021-09-22 18:13:12",
  "date": "2021-09-22",
  "sortOrder": -99,
  "code": " - utlis (folder contains GO files)\n  ---sendMail.go \n--templates (folder)\n --- reset_code.html\n - main.go"

我想向它添加对象的答案数组以使其成为嵌套对象,并使用 fetch/axios/async await 请求将更多对象添加到答案数组以使其像

"id": "2",
  "ques": "here is my second code ?",
  "quesBrief": "I can't seem to find it too.",
  "hashes": "#javascript , #goodlord",
  "author": "slowdeathv123",
  "dateTime": "2021-09-22 18:13:12",
  "date": "2021-09-22",
  "sortOrder": -99,
  "code": " - utlis (folder contains GO files)\n  ---sendMail.go \n--templates (folder)\n --- reset_code.html\n - main.go"
  "answers": [
    {
    "answerBrief": "Check under the bed",
    "answerCode": "no code sorry",
    "answerAuthor": "Sonya"
    },
    {
    "answerBrief": "Any other random solution",
    "answerCode": "no code sorry",
    "answerAuthor": "ABC"
    }
   ], 

如何创建发布请求以在对象内添加对象数组,同时检查答案数组是否已存在,如果不存在则创建一个并向其添加对象?

这有意义吗?

   let data = {
      "id": "2",
      "ques": "here is my second code ?",
      "quesBrief": "I can't seem to find it too.",
      "hashes": "#javascript , #goodlord",
      "author": "slowdeathv123",
      "dateTime": "2021-09-22 18:13:12",
      "date": "2021-09-22",
      "sortOrder": -99,
      "code": " - utlis (folder contains GO files)\n  ---sendMail.go \n--templates (folder)\n --- reset_code.html\n - main.go",
    };
      
    const newAnswer = {
      "answerBrief": "Check under the bed",
      "answerCode": "no code sorry",
      "answerAuthor": "Sonya"
    };
    
    const answers = [...data.answers || [], newAnswer];

    data = {
      ...data,
      answers
    }

如果您需要在 POST 请求之后添加答案:

fetch('your-api-url-to-add-answers', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data) // data with answers i think? 
})
.then(res => res.json())
.then(answersData => {
    const answers = [...data.answers || [], answeersData];
    data = {
      ...data,
      answers
    }
});

如果您需要发送带有更新答案的数据:

  const answers = [...data.answers || [], answeersData];
  const payload = {
     ...data,
     answers
  }

fetch('your-api-url-to-add-answers', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload) // data with answers i think? 
})
.then(res => res.json())
.then(answersData => {});

但要获得更准确的答案,请提供更多细节。 在 post 请求中需要发送哪些数据,以及从服务器收到什么样的响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM