如何添加一个新的对象数组到一个对象,使其嵌套,如果新添加的数组已经存在,添加另一个对象到该数组? &g



我有一个对象数组问题。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.htmln - main.go"

我想添加答案数组的对象,使其成为一个嵌套的对象,并添加更多的对象到答案数组使用fetch/axios/async等待请求,使其像

"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.htmln - 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"
}
], 

如何创建一个post请求来添加一个对象内的对象数组,同时检查是否答案数组已经存在,如果不创建一个并添加对象到它?

这有意义吗?

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.htmln - 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请求中需要发送什么数据,以及您从服务器接收到什么样的响应。

相关内容

  • 没有找到相关文章

最新更新