Javascript Variable Is An Array Of Objects But Can't Access The Elements
I am using Firebase database and Javascript, and I have code that will get each question in each category. I have an object called category will contain the name, the questions, an
Solution 1:
The callback(questionsPerCategory);
should happen when all async calls are finished.
Right now the questionsPerCategory
is not ready when the callback is called.
I would use Promise API
to accomplish this.
Depending on the Promise
library you are using, this can be accomplished in a different ways, e.g. by using bluebird it looks like you need map functionality.
Solution 2:
Try this code:
this.getQuestionsForEachCategory = function(callback, questions) {
var ref = firebase.database().ref('category');
var questionRef = firebase.database().ref('question');
console.log('get questions for each category');
var questionsPerCategory = [];
// CODE A
ref.once("value", function(snapshot) {
// CODE B
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var category = {
category_name: childData.category_name
};
// CODE C
questionRef.orderByChild("category_name").equalTo(childData.category_name).once("value", function(questionSnapshot){
var count = 0;
var q = [];
// CODE D
questionSnapshot.forEach(function(childQuestionSnapshot) {
var questionObj = childQuestionSnapshot.val();
count++;
questions.push(questionObj.question);
q.push(questionObj.question);
});
category.questions = q;
category.questionCount = count;
questionsPerCategory.push(category);
});
callback(questionsPerCategory);
});
});
};
Post a Comment for "Javascript Variable Is An Array Of Objects But Can't Access The Elements"