Прикрепить массив как атрибут к модулю из массива модулей? - PullRequest
0 голосов
/ 01 июня 2018

У меня есть два массива объектов, а именно: -

  1. Модули
  2. Ответы учащихся на вопросы (laq)

В моих модулях у меня есть объектысвойство с именем викторина, который имеет множество вопросов.Я хочу сравнить этот массив с ответами учащихся на вопросы (laq), массивом вложенных массивов.Если вопросы об ответах учащихся (laq) имеют массив, который совпадает с массивом вопросов в одном из Module.quiz из массива модулей, то я хочу прикрепить его к атрибуту вопросов об ответах учащихся (laq).Вопрос в массиве вопросов объекта «Модули» и вопрос в массиве «Массивы с ответами учащихся» имеет общее свойство текста.Используя это, я хочу сравнить, если оба массива равны, и если они равны, то присоедините массив из массивов с ответами на вопросы учащихся в качестве свойства к объекту модулей.

Например, рассмотрим: -

Modules = [module_1, module_2, module_3]
module1.quiz.questions = [question_1, question_2, question_3]
module2.quiz.questions = [question_4, question_5, question_6]
module3.quiz.questions = [question_7, question_8, question_9]

Learners_Answered_QUestions = [
    [question_7, question_8, question_9], 
    [question_1, question_2, question_3], 
    [question_4, question_5, question_6]
]

Я не могу сравнивать эти массивы напрямую, поскольку они имеют разные свойства.Поэтому я должен индивидуально проверить, все ли вопросы из массива одного из массивов Learner_Anspted_Questions имеют один и тот же вопрос в одном из свойств викторины модулей.

Вот мой код: -

for(var i = 0; i < $scope.modules.length; i++){
    for(var j = 0; j < $scope.laq.length; j++){
        if($scope.modules[i].quiz[0].questions.length === $scope.laq[j].length){
            var array_size = $scope.laq[j].length;
            for(var k = 0; k < array_size; k++){
                if($scope.modules[i].quiz[0].questions[k].text === $scope.laq[j][k].quiz_question.text){
                    $scope.attach = true;
                }
                else{
                    $scope.attach = false;
                };
            };
        };
        if($scope.attach === true){
            console.log($scope.attach);
            $scope.modules[i].lq_exists = true;
            $scope.modules[i].learner_quiz = $scope.laq[j];
            console.log($scope.modules[i]);
        }
    };
};

Мой код работает не так хорошо, и я хочу сделать его более надежным, даже если порядок вопросов в любом массиве изменен.

Вот пример формата json: -

module1.quiz = {
"url": "http://localhost:8080/api/registration_quiz/38/",
"id": 38,
"quiz_name": "Rakesh BIO",
"module_referred": "http://localhost:8080/api/registration_courses_modules/98/",
"questions": [
    {
        "url": "http://localhost:8080/api/registration_quiz_questions/109/",
        "quiz": "http://localhost:8080/api/registration_quiz/38/",
        "q_type": "MCQ",
        "text": "What is Rakesh's profession",
        "possible_answers": [
            {
                "url": "http://localhost:8080/api/registration_answer_options/306/",
                "text": "cook"
            },
            {
                "url": "http://localhost:8080/api/registration_answer_options/307/",
                "text": "Accountant"
            },
            {
                "url": "http://localhost:8080/api/registration_answer_options/308/",
                "text": "IT"
            },
            {
                "url": "http://localhost:8080/api/registration_answer_options/309/",
                "text": "Plumber"
            }
        ],
        "selected": null,
        "correct": {
            "url": "http://localhost:8080/api/registration_answer_options/308/",
            "text": "IT"
        }
    },
    {
        "url": "http://localhost:8080/api/registration_quiz_questions/110/",
        "quiz": "http://localhost:8080/api/registration_quiz/38/",
        "q_type": "MCQ",
        "text": "What is his place's name?",
        "possible_answers": [
            {
                "url": "http://localhost:8080/api/registration_answer_options/310/",
                "text": "Yavatmal"
            },
            {
                "url": "http://localhost:8080/api/registration_answer_options/311/",
                "text": "Dhule"
            },
            {
                "url": "http://localhost:8080/api/registration_answer_options/312/",
                "text": "Sangamner"
            },
            {
                "url": "http://localhost:8080/api/registration_answer_options/313/",
                "text": "Solapur"
            }
        ],
        "selected": null,
        "correct": {
            "url": "http://localhost:8080/api/registration_answer_options/311/",
            "text": "Dhule"
        }
    }
]

}

и JSON Learners_anspted_questions: -

lqa = [
    {
        "quiz_question": {
            "url": "http://localhost:8080/api/registration_quiz_questions/110/",
            "quiz": "http://localhost:8080/api/registration_quiz/38/",
            "q_type": "MCQ",
            "text": "What is his place's name?",
            "possible_answers": [
                {
                    "url": "http://localhost:8080/api/registration_answer_options/310/",
                    "text": "Yavatmal"
                },
                {
                    "url": "http://localhost:8080/api/registration_answer_options/311/",
                    "text": "Dhule"
                },
                {
                    "url": "http://localhost:8080/api/registration_answer_options/312/",
                    "text": "Sangamner"
                },
                {
                    "url": "http://localhost:8080/api/registration_answer_options/313/",
                    "text": "Solapur"
                }
            ],
            "selected": null,
            "correct": {
                "url": "http://localhost:8080/api/registration_answer_options/311/",
                "text": "Dhule"
            }
        },
        "learner": {
            "url": "http://localhost:8080/api/registration_learners/4/",
            "user": "http://localhost:8080/api/registration_custom_users/4/",
            "profile_picture": null,
            "courses_learning": "Django"
        },
        "chosen_option": {
            "url": "http://localhost:8080/api/registration_answer_options/250/",
            "text": "No Answer Selected"
        }
    },
    {
        "quiz_question": {
            "url": "http://localhost:8080/api/registration_quiz_questions/109/",
            "quiz": "http://localhost:8080/api/registration_quiz/38/",
            "q_type": "MCQ",
            "text": "What is Rakesh's profession",
            "possible_answers": [
                {
                    "url": "http://localhost:8080/api/registration_answer_options/306/",
                    "text": "cook"
                },
                {
                    "url": "http://localhost:8080/api/registration_answer_options/307/",
                    "text": "Accountant"
                },
                {
                    "url": "http://localhost:8080/api/registration_answer_options/308/",
                    "text": "IT"
                },
                {
                    "url": "http://localhost:8080/api/registration_answer_options/309/",
                    "text": "Plumber"
                }
            ],
            "selected": null,
            "correct": {
                "url": "http://localhost:8080/api/registration_answer_options/308/",
                "text": "IT"
            }
        },
        "learner": {
            "url": "http://localhost:8080/api/registration_learners/4/",
            "user": "http://localhost:8080/api/registration_custom_users/4/",
            "profile_picture": null,
            "courses_learning": "Django"
        },
        "chosen_option": {
            "url": "http://localhost:8080/api/registration_answer_options/306/",
            "text": "cook"
        }
    }
]

1 Ответ

0 голосов
/ 01 июня 2018

Для целей этого вопроса я упростил JSON только до того, что имеет отношение.

Найдите полностью работающий алгоритм ниже (вы можете поиграть и изменить длины или тексты, чтобы проверить все случаи)

var modules = [
        {
            "id": 38,
            "questions": [
                {
                    "text": "What is Rakesh's profession"
                },
                {
                    "text": "What is his place's name?"
                }
            ]
        },
        {
            "id": 39,
            "questions": [
                {
                    "text": "What is Protozoid's profession"
                },
                {
                    "text": "What is his car's name?"
                }
            ]
        }
    ];
    
var laq = [
        [{
            "quiz_question": {
                "text": "What is his place's name?"
            }
        },
        {
            "quiz_question": {
                "text": "What is Rakesh's profession"
            }
        }],

        [{
            "quiz_question": {
                "text": "What is Protozoid's profession"
            }
        },
        {
            "quiz_question": {
                "text": "This shouldnt be attached because not all questions match"
            }
        }]
    ];
    
modules.forEach(function (module) {
	var shouldAttach = true;
	var lqReference = [];
	
	laq.forEach(function (laqItem) {
		var matchedCount = 0;
		module.questions.forEach(function (moduleQuestion) {
			
			laqItem.forEach(function (laqItemQuestion) {

        		// console.log(moduleQuestion.text, laqItemQuestion.quiz_question.text, moduleQuestion.text == laqItemQuestion.quiz_question.text);
				if (moduleQuestion.text == laqItemQuestion.quiz_question.text) {
					matchedCount++;
				}

			});

		});
      
  		// console.log("should attach1", matchedCount, laqItem.length);
		if (matchedCount == laqItem.length) {
    		shouldAttach = true; 
			lqReference = laqItem;
		} else {
			matchedCount = 0;
		}
   		
   		// console.log("should attach2", shouldAttach);
		// If questions matched but different lengths
		if (shouldAttach && module.questions.length !== lqReference.length) {
			shouldAttach = false;
		}
	});

  	// console.log("should attach3", shouldAttach);
	if (shouldAttach) {
		module.lq_exists = true;
		module.learner_quiz = lqReference;
	}
});

console.log(modules);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...