У меня есть два массива объектов, а именно: -
В моих объектах Modules у меня есть свойство под названием quiz, в котором есть массив вопросов. Я хочу сравнить этот массив с ответами учащихся на вопросы (laq), массивом вложенных массивов. Если ответы на вопросы учащихся (laq) имеют массив, который соответствует массиву вопросов в одном из Module.quiz среди массива модулей, тогда я хочу присоединить к нему атрибут ответов на вопросы учащихся (laq). Вопрос в массиве вопросов объекта «Модули» и вопрос в массиве массивов «Ответы учащихся» имеют общее свойство текста. Используя это, я хочу сравнить, равны ли оба массива, и если они равны, то присоедините массив из массивов ответов учащихся на вопросы как свойство к объекту Modules.
Например, рассмотрите: -
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_Ansarded_Questions содержат один и тот же вопрос в одном из свойств Modules Quiz.
Вот мой код: -
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.info($scope.attach);
$scope.modules[i].lq_exists = true;
$scope.modules[i].learner_quiz = $scope.laq[j];
console.info($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"
}
}
]
}
и Learners_anseled_questions JSON: -
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"
}
}
]
Да, конечно!! подождите минуту.....
Кроме того, ваш $scope.attach будет либо истинным, либо ложным в зависимости от последнего сравнения ... потому что вы переопределяете предыдущее значение на каждой итерации. Вместо этого вы можете определить его как false перед циклом for и установить как true, как только найдете соответствующий вопрос.
Да, если в массиве, даже если текст одного вопроса не совпадает, я не хочу выполнять дальнейшую обработку.
Ах, хорошо ... но учтите это в своем коде: если последнее сравнение совпадает, $scope.attach будет установлен в значение true ... даже если все предыдущие не совпадают.
Ах, да!!! Благодарю.
Спасибо за добавление примеров JSON. Другой вопрос ... правильно ли то, что вы пытаетесь достичь, - это проверить, завершен ли moduleX, сравнив все вопросы внутри moduleX со всеми вопросами во всех вопросах, на которые даны ответы учащихся (laq)?
Позвольте нам продолжить обсуждение в чате.
да, я хочу иметь одинаковое количество вопросов и одинаковый текст для каждого вопроса в обоих сравниваемых массивах. порядок не имеет значения.
Черт возьми, это было сложно, надеюсь, мой ответ ниже - это то, что вы искали.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Для этого вопроса я упростил 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.info(moduleQuestion.text, laqItemQuestion.quiz_question.text, moduleQuestion.text == laqItemQuestion.quiz_question.text);
if (moduleQuestion.text == laqItemQuestion.quiz_question.text) {
matchedCount++;
}
});
});
// console.info("should attach1", matchedCount, laqItem.length);
if (matchedCount == laqItem.length) {
shouldAttach = true;
lqReference = laqItem;
} else {
matchedCount = 0;
}
// console.info("should attach2", shouldAttach);
// If questions matched but different lengths
if (shouldAttach && module.questions.length !== lqReference.length) {
shouldAttach = false;
}
});
// console.info("should attach3", shouldAttach);
if (shouldAttach) {
module.lq_exists = true;
module.learner_quiz = lqReference;
}
});
console.info(modules);
Не могли бы вы включить примеры двух JSON? Вы все объяснили, но все еще сложно уследить. Спасибо