fullyconnected fullyconnected - 1 year ago 121
Ajax Question

Unable to loop through JSON reponse in JQuery with .each method

I'm unable to extract object properties using the . each() method in Jquery. I'm able to view the full response with console.log (result), but I'm unable to extract from that response. I receive an undefined or [Object object] message when I attempt to use result.snippet in the .each method. When I use the .each for other json responses I'm able to extract by using data.value, but for this response it doesn't work.

(function getArticles(){

var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "",
'q': "obama"


url: url,




}).done(function(result) {

$.each(result, function () {

document.write(result.snippet); // This is not working, but works with other json responses from other API's//




Picture of JSON response

Answer Source

The response you're getting is an object, not an array. You can't iterate over an object. You can iterate over the keys of an object and then reference each key. In either case, you don't need jQuery to do the iteration.

var response = {
  "hello": "world",
  "foo": "bar"

for (var key in response) {
  console.log(key, response[key]);

In your case, to get to the snippet:


You could iterate each document:

response.docs.forEach(function(doc) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download