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()
2
  • console.log is showing values? Commented Jun 24, 2013 at 13:24
  • @AnkitJaiswal There is no Ajax call there! Commented Jun 24, 2013 at 13:38

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.