kramer65 kramer65 - 5 months ago 14
Javascript Question

How to print out object properties within for-in loop?

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!

Answer

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