Reputation: 207
I am trying to return an array of surnames from a json query to form part of a section which can be chosen by a user.
$.ajax({
url: 'https://reqres.in/api/users?page=1',
type: "GET",
success: function (response) {
console.log(response);
original = convState.current;
State.current.next = State.newState({
type: 'select',
question: ['Please select'],
answer: [{text: [response.data[0].last_name], value: 'true'}],
});
The current result only returns the one surname bluth
from the json which can be found at https://reqres.in/api/users?page=1
If I try and add a loop to access the array, absolutely nothing happens. The html page just waits for something to happen, which never happens. Can some please help met rectify the loop, I am not sure where and how I should add it. I tried here, but then the page waits for nothing to ever happen.
var len = data.length;
for(var i=0;i<len;i++){
answer: [{text: [response.data[i].last_name], value: 'true'}],
}
Upvotes: 0
Views: 67
Reputation: 1144
I would check your console log to see if any errors are occurring. The provided for
loop did not work for me. However, the AJAX query works and I am able to loop through the array by modifying your for
loop. Look at my example code.
EDIT: I understand what is happening in your code. You tried implementing a for
loop within creating an object (which does not work). My sample code aggregates all of the last names into an array and then uses that for creating a new state. I'm not sure if you wanted multiple new states, or one state with multiple answers.
$.ajax({
url: 'https://reqres.in/api/users?page=1',
type: "GET",
success: function (response) {
let data = response.data;
let array = [];
for(var i = 0; i < data.length; ++i) {
let account = data[i];
let info = {text: [account.last_name], value: 'true'};
array.push(info);
}
console.log(array);
// Now do something with the array...
original = convState.current;
State.current.next = State.newState({
type: 'select',
question: ['Please select'],
answer: array
}
});
Or if you would like to using the map
function to simplify array creation, you can do the following.
$.ajax({
url: 'https://reqres.in/api/users?page=1',
type: "GET",
success: function (response) {
let data = response.data;
let array = data.map((account) => Object.create({text: [account.last_name], value: 'true'}));
console.log(array)
// Now do something with the array...
original = convState.current;
State.current.next = State.newState({
type: 'select',
question: ['Please select'],
answer: array
}
}
});
Upvotes: 2