Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

Javascript: Iterate over an array of objects nested within an object as a value

I am fairly new to working with APIs in Javascript and I am working on a quiz app project that makes use of a quiz question generator API. I have figured out how to display the API response in the console to view the Javascript object? string? (I have used typeof on the response which tells me it is a string), and now I am trying to figure out how to extrapolate information such as questions, correct answer, and incorrect answer(also an array) from the value for result that seems to be an array of objects. Any help regarding this issue would be greatly appreciated!

 var request = new XMLHttpRequest();

request.open('Get', 'MyAPIKey', true);

request.onload = function() {
 console.log(request.status);
 console.log(request.response);
};

enter image description here

Blockquote

enter image description here

Blockquote enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
request.onload = function() { 
   let res = JSON.parse(request.response);

   console.log(typeof res);
   console.log(res);
};

first you need to convert this to a JSON Object so that you can be able to work with it in your data, the very first line on this function is doing that for you. if you log the type of this on the console you will see object not string. I hope this help. thanks for asking this question, i like it because it gave me a lot of trouble while learning how to code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...