0

I'm getting a list of objects from an API which looks like this:

{
  "results": [
    {
      "date": "2014-09-25 19:00:00", 
      "title": "Hitjeskanon"
    }, 
    {
      "date": "2014-09-25 21:00:00", 
      "title": "Black & White ESN House & Techno"
    }, 
    {
      "date": "2014-09-25 21:00:00", 
      "title": "Hit It!"
    }
  ]
}

I now get these results from the API, and want to log them, which I try as follows:

$.ajax({
    url: "/eventSearch/" + q,
    cache: false,
    success: function(result) {
        console.log(result);
        console.log(result['results']);
        for (event in result['results']) {
            console.log(event['title']);
        }
    }
});

In the console, I correctly see the objects with the first two logs, but the console.log(event['title']) only prints out undefined.

What am I doing wrong here? All tips are welcome!

Unihedron
  • 10,902
  • 13
  • 62
  • 72
kramer65
  • 50,427
  • 120
  • 308
  • 488

2 Answers2

3

result['results'] is actually an Array. So, you should iterate it with normal for loop like this

for (var i = 0; i < result['results'].length; i += 1) {
    console.log(result['results'][i]['title']);
}

Or you can use Array.prototype.forEach like this

result['results'].forEach(function(currentObject) {
    console.log(currentObject['title']);
});

Also, you can access the attributes with the dot operator, like this

    console.log(result.results[i].title);

or

    console.log(currentObject.title);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    ... and of course `result.results[i].title` would work too :) – Pointy Oct 01 '14 at 14:37
  • Also see http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea for more discussion on this `for-in` with JavaScript arrays problem. – Travis Hohl Oct 01 '14 at 15:53
0

You could use a traditional for loop, but if you don't need random access (e.g., results[2]) you can use a for...of statement (introduced in ECMAScript6). In your code, just change for...in to for...of:

$.ajax({
    url: "/eventSearch/" + q,
    cache: false,
    success: function(result) {
        console.log(result);
        console.log(result['results']);
        for (event of result['results']) {
            console.log(event['title']);
        }
    }
});

And like @thefourtheye mentioned, you can access the results array and the event's title property with the dot operator:

$.ajax({
    url: "/eventSearch/" + q,
    cache: false,
    success: function(result) {
        console.log(result);
        console.log(result.results);
        for (event of result.results) {
            console.log(event.title);
        }
    }
});

This page is a great reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Travis Hohl
  • 2,176
  • 2
  • 14
  • 15