У меня есть вопросы, которые я пытаюсь повторить, и в каждом вопросе могут быть подвопросы, я хочу повторить их все: - мои переменные: -
Questions:[],
current_question : [],
check_box_answers: [],
got_subquestion: false,
sub_Questions :[],
iterator : 0,
subQuestion_iterator:-1,
Это мой объект данных: - и вот моя функция, когда я отправляю значение, которое хочу получить следующий вопрос, и проверяю, есть ли в нем подвопросы или нет, если они есть, затем перебираю вспомогательные вопросы, и когда они заканчивают, вернитесь к основным вопросам, вот что данные json выглядят так: -
{
"title": "asd",
"sub_questions": [],
"section_title": "asdaa",
"type": "radio",
"answers": [
{
"uuid": "56907C80-FD7D-4F83-8C25-3FBA1CD9A060",
"title": "1-3 asd"
},
{
"uuid": "A71EF3F5-2F02-44A2-ABC9-085D52AB450E",
"title": "4-10"
},
{
"uuid": "67EF9833-D39D-4A07-9974-6B1926474AF2",
"title": "asd 10"
}
]
},
{
"uuid": "D6F7785B-163E-4EFF-8F79-EE01F579E2A2",
"title": "asdsda",
"sub_questions": [
{
"uuid": "8995B5A7-E698-47EF-9ADE-8107EAA13A16",
"title": "asdda",
"section_title": "dasdsa",
"type": "radio",
"answers": [
{
"uuid": "413DA1A7-2B44-4B06-9713-FB2A0020392F",
"title": "asda"
},
{
"uuid": "056ADC3A-C528-4615-9272-19EFAB73013F",
"title": "asdsda"
},
{
"uuid": "419B7C68-1032-448F-97EE-8A361605C693",
"title": "asdsdasda"
},
{
"uuid": "DC60E085-EDAB-49E1-B11A-A13C423B08B8",
"title": "asdsdad"
}
]
}
моя функция выглядит так: -
getNextQuestion(){
var app = this
// check if got_matrix = false
if (app.got_matrix === false) {
app.iterator = app.iterator+1
console.info('iterator = ' + app.iterator)
app.current_question = app.Questions[app.iterator]
if (app.current_question.sub_questions.length > 0) {
// first time matrix occurs
console.info('first time matrix occurs')
app.got_matrix = true
app.sub_Questions = app.current_question.sub_questions
console.info(app.sub_Questions)
}
}
if (app.got_matrix === true) {
// we have sub_questions
console.info(app.sub_Questions.length)
if (app.subQuestion_iterator+1 === app.sub_Questions.length ) {
// we are done iterating through all the matrix
console.info('no more sub_Questions')
app.got_matrix = false
app.subQuestion_iterator = 0
// get the next normal question
app.iterator = app.iterator+1;
app.current_question = app.Questions[app.iterator]
}else{
// one more sub question
console.info('one more sub question ')
app.subQuestion_iterator = app.subQuestion_iterator+1
console.info('sub_iterator = ' + app.subQuestion_iterator)
app.current_question = app.sub_Questions[app.subQuestion_iterator]
}
}
не хватает вопросов, где я напортачил?



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


Как насчет того, чтобы все вопросы выровнять в линейную форму?
const flatten = (collection, property) => (collection || []).reduce((accumulator, item) => (
accumulator.concat(item, flatten(item[property]))
), []);
const flattenedQuestions = flatten(yourQuestions, 'sub_questions');
Теперь ответить на следующий вопрос так же просто, как наткнуться на app.iterator:
const app = {
iterator: 0,
};
const getNextQuestion = index => flattenedQuestions[index];
getNextQuestion(app.iterator++);
getNextQuestion(app.iterator++);
getNextQuestion(app.iterator++);
Мой ответ безошибочный и направит вас в правильном направлении. collection - это то, что вы передаете в flatten(). Это должен быть массив, а не объект. Ваш app.Questions должен быть массивом вопросов.
он возвращает эту ошибку "(collection || []). reduce не является функцией", можете ли вы проверить это? или положить на codePen или любое исполняемое место / файл ??