for in in для оператора вставки последнего значения формы - PullRequest
0 голосов
/ 05 мая 2018

Требования: У меня есть формы вопросов и ответов, где вопросы являются динамическими, я должен отправить выбранные пользователем ответы в 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"
  }
]

поэтому у меня есть 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 и answer в конечном объекте. Я застрял, и помощь будет оценена. Заранее спасибо.

1 Ответ

0 голосов
/ 05 мая 2018

Уверен, ваш 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
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...