关于返回需要的json格式

sakixi / 2023-08-10 / 原文

在做考试页面的时候,在获取答案时,得到的数据格式的处理

  // 循环每一个选了的单选框
          $('input[type="radio"]:checked').each(function (i) {
              var questionAnswer = {};
              var answer = $(this).val();
              var choice_id = $(this).attr("name");
              var question_type = $(this).attr("quetype");
              // console.log(answer + "=======" + choice_id + "============" + question_type);  //log单选框的值
              questionAnswer.question_type = question_type;
              questionAnswer.choice_id = choice_id;
             questionAnswer.answer = answer;
             questionAnswers.push(questionAnswer);//每一次赋值完就把questionAnswer push到questionAnswers数组中去储存
         })
 // 循环每一个选了的复选框
         $('input[type="checkbox"]:checked').each(function () {
             var questionAnswer = {};
             var choice_id = $(this).attr("queid");
             var question_type = $(this).attr("quetype");
             var answer = $(this).val();
             // console.log(answer + "======" + choice_id + "==========" + question_type);  //log单选框的值
             questionAnswer.question_type = question_type;
             questionAnswer.choice_id = choice_id;
             questionAnswer.answer = answer;
             checkboxquestionAnswers.push(questionAnswer);
         })
         var map = {},dest = [];
//循环存储复选框值的 checkboxquestionAnswers 数组将同一id不同answer的合并为一个对象
for (var i = 0; i < checkboxquestionAnswers.length; i++) { var ai = checkboxquestionAnswers[i]; if (!map[ai.choice_id]) { dest.push({ choice_id: ai.choice_id, question_type: ai.question_type, answer: [ai.answer], }); map[ai.choice_id] = ai; } else { for (var j = 0; j < dest.length; j++) { var dj = dest[j]; if (dj.choice_id == ai.choice_id) { dj.answer.push(ai.answer); break; } } } } questionAnswers.push(...dest);//把dest数组转换成对象push到questionAnswers数组中去 console.log(questionAnswers);

最终得到的格式是:

[
    {
        "question_type": "1",
        "choice_id": "choid-640-201",
        "answer": "A"
    },
    {
        "question_type": "1",
        "choice_id": "choid-923-2",
        "answer": "D"
    },
    {
        "question_type": "3",
        "choice_id": "choid-840-1",
        "answer": "正确"
    },
    {
        "choice_id": "choid-551-101",
        "question_type": "2",
        "answer": [
            "A",
            "B",
            "C",
            "D"
        ]
    },
    {
        "question_type": "4",
        "choice_id": "choid-020-51",
        "answer": "就会\n"
    }
]

一个关于把index赋值到对象中的方法

   arr.map((item, index) => (item.seq_no = index + 1));
//得到的数据格式就变成这样了
{
        "question_type": "1",
        "choice_id": "choid-000-00",
        "answer": "A",
        "seq_no":index
 }