I have an array of objects questions.json which looks like
"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"
I want to add answers array of objects to it to make it a nested object and add more objects to answers array using a fetch/axios/async await request to make it like
"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"
}
],
How to create a post request to add an array of objects inside an object while checking if the answers array already exists, if not create one and add objects to it?
Does this make sense?
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
}
If you need to add answers that comes after POST request:
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
}
});
If you need to send data with updated 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 => {});
But for a more accurate answer, provide a little more detail. What data needs to be sent in a post request, and what kind of response you receive from the server.