James Parsons
James Parsons

Reputation: 925

How to create an array from AJAX response

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
  })
];

Upvotes: 2

Views: 1774

Answers (2)

Tomalak
Tomalak

Reputation: 338128

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;
});

Upvotes: 3

Marcelo Abiarraj
Marcelo Abiarraj

Reputation: 309

You can do something like this:

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

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

Upvotes: 0

Related Questions