Как использовать ax ios get call для отправки ответа vuejs - PullRequest
0 голосов
/ 05 мая 2020

Я создаю приложение vue, и мне нужна помощь.

Я получаю вложенный json из вызова ax ios get, и мне нужно установить определенную часть c ответа на мои данные.

Это мой ответ:

[
    {
        "id": 1,
        "survey_title": "questionnaire TIC TAC",
        "company": {
            "companyId": 1,
            "company_type": "TPE",
            "models": [
                {
                    "modelId": 1,
                    "model_title": "Questionnaire TPE",
                    "topics": [
                        {
                            "topicId": 1,
                            "topic_title": "Sécurité des systèmes d'informations",

                            "questions": [
                                {
                                    "questionId": 1,
                                    "question_title": "Avez-vous, un jour, procédé à un audit de sécurité du système d'information de votre entreprise par une entreprise externe ?",                                    
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu"

                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non"

                                        },
                                        {
                                            "answerId": 3,
                                            "answer_title": "Une fois"

                                        },
                                        {
                                            "answerId": 4,
                                            "answer_title": "Récemment"

                                        },
                                        {
                                            "answerId": 5,
                                            "answer_title": "Régulièrement"

                                        }
                                    ]
                                },
                                {
                                    "questionId": 2,
                                    "question_title": "Avez-vous procédé à un inventaire des OS & logiciels, installés sur le matériel fixe et portable de l'entreprise ?",                                    
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu"                                         
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non"                                           
                                        },
                                        {
                                            "answerId": 5,
                                            "answer_title": "Régulièrement"                                            
                                        },
                                        {
                                            "answerId": 6,
                                            "answer_title": "Occasionnellement"                                            
                                        },
                                        {
                                            "answerId": 11,
                                            "answer_title": "Peu"                                        
                                        }
                                    ]
                                },


                            ]
                        },
                        {
                            "topicId": 2,
                            "topic_title": "Sécurité du réseau",
                            "topic_max_quote": 16,
                            "questions": [
                                {
                                    "questionId": 10,
                                    "question_title": "Présence d'un pare-feu ?"                                  
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu"                                          
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non"                                        
                                        },
                                        {
                                            "answerId": 18,
                                            "answer_title": "Oui mais il n'est pas mis à jour"                                        
                                        },
                                        {
                                            "answerId": 19,
                                            "answer_title": "Oui mis à jour régulièrement"                                         
                                    ]
                                },
                                {
                                    "questionId": 11,
                                    "question_title": "Les appareils importants sont-ils reliés à un onduleur ?",
                                    "answers": [
                                        {
                                            "answerId": 1,
                                            "answer_title": "Inconnu"                                          
                                        },
                                        {
                                            "answerId": 2,
                                            "answer_title": "Non"                                          
                                        },
                                        {
                                            "answerId": 20,
                                            "answer_title": "En partie"                                          
                                        }
                                        {
                                            "answerId": 21,
                                            "answer_title": "Oui"                                         
                                        }
                                    ]
                                },

                            ]
                        }
                    ]
                }
            ]
        }
    }
]

И мой скрипт:

data: () => ({

    currentSurveys: [],
    allQuestionsIds: []
  }),

mounted() {
    axios
      .get(`http://localhost:3005/surveys/` + this.$route.params.id)
      .then(response => {
        this.currentSurveys = response.data;
      })
      .catch(e => {
        console.log(e);
      });
  },

Я хочу, чтобы pu sh all "questionId" в allQuestionsIds: []. Я считаю, что мне нужно вставить al oop в мой вызов ax ios, но я не знаю, как.

Есть идеи?

Большое спасибо.

1 Ответ

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

Прежде всего, имейте в виду, такой тип вложенных данных, с которыми вы имеете дело, не является подходящим подходом для передачи данных, и вам следует подумать о том, чтобы разбить их на маленькие части. Кроме того, в предоставленных вами данных была опечатка, которую мне удалось исправить. Чтобы получить questionId из предоставленных вами данных, вы должны определить вложенные l oop следующим образом:

const allQuestionsIds = [];

const currentSurveys = [{
  id: 1,
  survey_title: "questionnaire TIC TAC",
  company: {
    companyId: 1,
    company_type: "TPE",
    models: [{
      modelId: 1,
      model_title: "Questionnaire TPE",
      topics: [{
          topicId: 1,
          topic_title: "Sécurité des systèmes d'informations",

          questions: [{
              questionId: 1,
              question_title: "Avez-vous, un jour, procédé à un audit de sécurité du système d'information de votre entreprise par une entreprise externe ?",
              answers: [{
                  answerId: 1,
                  answer_title: "Inconnu"
                },
                {
                  answerId: 2,
                  answer_title: "Non"
                },
                {
                  answerId: 3,
                  answer_title: "Une fois"
                },
                {
                  answerId: 4,
                  answer_title: "Récemment"
                },
                {
                  answerId: 5,
                  answer_title: "Régulièrement"
                }
              ]
            },
            {
              questionId: 2,
              question_title: "Avez-vous procédé à un inventaire des OS & logiciels, installés sur le matériel fixe et portable de l'entreprise ?",
              answers: [{
                  answerId: 1,
                  answer_title: "Inconnu"
                },
                {
                  answerId: 2,
                  answer_title: "Non"
                },
                {
                  answerId: 5,
                  answer_title: "Régulièrement"
                },
                {
                  answerId: 6,
                  answer_title: "Occasionnellement"
                },
                {
                  answerId: 11,
                  answer_title: "Peu"
                }
              ]
            }
          ]
        },
        {
          topicId: 2,
          topic_title: "Sécurité du réseau",
          topic_max_quote: 16,
          questions: [{
              questionId: 10,
              question_title: "Présence d'un pare-feu ?",
              answers: [{
                  answerId: 1,
                  answer_title: "Inconnu"
                },
                {
                  answerId: 2,
                  answer_title: "Non"
                },
                {
                  answerId: 18,
                  answer_title: "Oui mais il n'est pas mis à jour"
                },
                {
                  answerId: 19,
                  answer_title: "Oui mis à jour régulièrement"
                }
              ]
            },
            {
              questionId: 11,
              question_title: "Les appareils importants sont-ils reliés à un onduleur ?",
              answers: [{
                  answerId: 1,
                  answer_title: "Inconnu"
                },
                {
                  answerId: 2,
                  answer_title: "Non"
                },
                {
                  answerId: 20,
                  answer_title: "En partie"
                },
                {
                  answerId: 21,
                  answer_title: "Oui"
                }
              ]
            }
          ]
        }
      ]
    }]
  }
}];

currentSurveys.forEach((item) => { // currentSurveys should be your response.data which is this.currentSurveys in your case
  item.company.models.forEach((model) => {
    model.topics.forEach((topic) => {
      topic.questions.forEach((question) => {
        allQuestionsIds.push(question.questionId); // allQuestionsIds should be replace with this.allQuestionsIds in your Vue application
      });
    });
  });
});

console.log(allQuestionsIds);

ПРИМЕЧАНИЕ: Я только что определил allQuestionsIds и currentSurveys как const s, чтобы предоставить живую демонстрацию, вы должны пропустить их объявления переменных а затем замените allQuestionsIds.push(newThirdItem.questionId); на this.allQuestionsIds.push(newThirdItem.questionId);, а также замените currentSurveys на this.currentSurveys в своем приложении Vue.

...