Reputation: 2251
I'm retrieving data from
https://api.instagram.com/v1/tags/HASHTAG/media/recent?client_id=CLIENT_ID
where
HASHTAG = the hashtag I'm searching
CLIENT_ID = my client id
I am having no trouble retrieving the picture urls and captions but when I try to get the comments the comments are being returned as 'undefined'.
The data is stored in an array called pictures so if I want to get the standard resolution url I just do:
for(i = 0; i < pictures.length; i++){
pictureURL[i] = pictures[i].images.standard_resolution.url;
}
Right now the code I'm trying to use to retrieve the comments is :
//where 'i' is the index of the pic I'm currently focusing on
for (comment in pictures[i].comments.data) {
alert(comment.text);
//using alert just to see what is being retrieved
}
But the issue is that the alerts are only displaying 'undefined' and also they are only displaying undefined when there is a comment (I checked on my phone, if the pic has no comment, there is no alert. If the picture has comments there is 1 alert for each comment.
Can someone please help me out?
Upvotes: 0
Views: 292
Reputation: 115920
The value in pictures[i].comments.data
is an array, as shown in the "Response" section in the /tags/tag-name/media/recent
Instagram API docs:
[{
"type": "image",
...
"comments": {
"data": [{
"created_time": "1296703540",
"text": "Snow",
...
},
{
"created_time": "1296707889",
"text": "#snow",
...
}],
...
As you can see, the data
property in the comments
object is an array (beginning with [
).
You're misusing for..in
on an array. (See Why is using "for...in" with array iteration a bad idea?) for..in
loops over property names of objects. The value of comment
will always be a property name string, which certainly has no text
property.
Instead, you need a plain for
loop, because pictures[i].comments.data
is an array:
for (var j=0; j<pictures[i].comments.data.length; j++) {
var comment = pictures[i].comments.data[j];
alert(comment.text)
}
One important note is that even if pictures[i].comments.data
had been a non-array object, your use of for..in
still wouldn't be quite right. Your variable comment
holds property names, and you need to use property-access to get the value that a property name refers to:
for (commentKey in pictures[i].comments.data) {
var commentValue = pictures[i].comments.data[commentKey];
alert(commentValue.text)
}
Note that this might work for arrays, but:
Upvotes: 1