2

I have an array called questionSets full of objects. The createSet function should create new or create a copy of an existing questionSets object. The function getQuestionsFromSet is used if createSet is used to make a copy. For some reason when I call getQuestionsFromSet() from inside createSet() I always get a returned value of 'undefined'. I can't figure out why because when I do a console.log() of the value to be returned by getQuestionsFromSet() I see exactly what I want.

I have these two functions.

function createSet(name, copiedName) {
    var questions = [];
    if (copiedName) {
        questions = getQuestionsFromSet(copiedName);
    }
    console.log(questions); // undefined. WHY??
    questionSets.push({
        label: name,
        value: questions
    });
}; // end createSet()

function getQuestionsFromSet(setName) {
    $.each(questionSets, function (index, obj) {
        if (obj.label == setName) {
            console.log(obj.value); // array with some objects as values, which is what I expect.
            return obj.value;
        }
    });
}; // end getQuestionsFromSet()
Ben
  • 2,917
  • 10
  • 28
  • 47

2 Answers2

8

Because getQuestionsFromSet() does not return anything and so is implicitly undefined.

What you need is probably something like:

function getQuestionsFromSet(setName) {
    var matched = []; // the array to store matched questions..
    $.each(questionSets, function (index, obj) {
        if (obj.label == setName) {
            console.log(obj.value); // array with some objects as values, which is what I expect.
            matched.push(obj.value); // push the matched ones
        }
    });
    return matched; // **return** it
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135
2

return obj.value; is nested within the inner $.each(function{}), and getQuestionsFromSet is indeed not returning anything.

haim770
  • 48,394
  • 7
  • 105
  • 133