2

All seems like it should be very simple but I am having issues.

I would like to create an array and list all 'questions' within the array from an AJAX response using jQuery.

I gather my thinking is out as question just returns a higher level object containing all data.

var questions = response.questions;
console.log(response.questions);

var question = [
  $.each(questions, function (value) {
   value.question
  })
];
1
  • What does response.questions look like? Commented Dec 7, 2016 at 19:16

2 Answers 2

3

Assuming that response looks like this:

{
    questions: [
        {question: 'A'},
        {question: 'B'},
        {question: 'C'}
    ]
}

and you want

['A', 'B', 'C']

then .map() is what you are looking for.

var question = $.map(response.questions, function (item) {
   return item.question;
});
Sign up to request clarification or add additional context in comments.

2 Comments

How would I then map the index of the questions to get, ['0' , '1' , '2'] for example?
I'm not sure what you mean by that. The index is provided as the second argument to the .map() callback, if you need it for anything. (Next time, please ask a complete question. Input sample, corresponding desired output and a short paragraph of what you intend to do in the bigger picture. Debugging an incomplete question via the comment section is tedious and overall very inefficient.)
0

You can do something like this:

var questions = response.questions;
console.log(response.questions);    

question = []
for(var q of questions){
    question.push(q)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.