需求:我有问答表单,在这些表单中,问题是动态的,我必须将用户选择的答案发送到。我应该以以下格式发送数据。
"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"
}
]因此,我有questionId和来自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"
}
]请注意,我在最终对象中得到了相同的answerId和答案。我被困住了,我们会感谢你的帮助。提前谢谢。
发布于 2018-05-05 05:55:10
非常肯定,您的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
}https://stackoverflow.com/questions/50185939
复制相似问题