要求: 我有问题和动态的问答形式,我必须将用户选择的答案发送给API。我应该以下面的格式发送数据。
"title" : "test title",
"clientId" : 1,
"categoryId" : 1,
"serviceId" : 1,
"steps" : [
{
"questionId" : "1",
"question" : "what is your name",
"answerId" : "1",
"answer" : "John Doe"
},
{
"questionId" : "2",
"question" : "what is your age",
"answerId" : "2",
"answer" : "32"
}
]
所以我有问题和问题来自API和answerId以及用户输入表格的答案现在我试图通过循环搜索下面的问题和答案来结合上述格式的问题和答案:
var step = [];
var innerArray = {}
var QuestionsFormData = this.CreateServiceQuestionsForm.value;
for (var i=0; i < this.getQuestionsData.length; i++){
for(var key in this.CreateServiceQuestionsForm.controls) {
if(this.CreateServiceQuestionsForm.controls.hasOwnProperty(key)) {
console.log(this.CreateServiceQuestionsForm.controls[key]);
innerArray = {
"questionId" : this.getQuestionsData[i].id,
"question" : this.getQuestionsData[i].question,
"answerId" : key,
"answer" : this.CreateServiceQuestionsForm.controls[key].value,
}
}
}
step.push(innerArray);
}
这就是我得到的:
"steps" : [
{
"questionId" : "1",
"question" : "what is your name",
"answerId" : "5",
"answer" : "you city is bla bla"
},
{
"questionId" : "2",
"question" : "what is your age",
"answerId" : "5",
"answer" : "your city is bla bla"
},
{
"questionId" : "3",
"question" : "what is your profession",
"answerId" : "5",
"answer" : "your city is bla bla"
}
]
请注意,我在最终对象中得到了相同的答案和答案。 我被困住了,我将不胜感激。提前谢谢。
答案 0 :(得分:0)
非常确定您的steps.push(innerArray)
需要更深一层。现在它只针对每个问题推送一个对象。 不为每个答案推送一个新的innerAray
对象。它只推送最后一个innerArray
值,因为所有其他值只是在下一次迭代中被覆盖而没有被推送到整个记录数组。
var step = [];
var innerArray = {}
var QuestionsFormData = this.CreateServiceQuestionsForm.value;
for (var i=0; i < this.getQuestionsData.length; i++){
for(var key in this.CreateServiceQuestionsForm.controls) {
if(this.CreateServiceQuestionsForm.controls.hasOwnProperty(key)) {
console.log(this.CreateServiceQuestionsForm.controls[key]);
innerArray = {
"questionId" : this.getQuestionsData[i].id,
"question" : this.getQuestionsData[i].question,
"answerId" : key,
"answer" : this.CreateServiceQuestionsForm.controls[key].value,
}
}
step.push(innerArray) // < --- but it should be here
}
// < --- step.push(innerArray) is currently here
}