0

I am sending a GET request to YouTube playlistItems API and I get the data object, and after that I iterate through all of the items with the help of a $.each() loop and in the loop I add every single element (object) into a new array. I am having troubles reading that array any help is appreciated. CODE:

var videosArray = new Array();
$.get('https://www.googleapis.com/youtube/v3/playlists', {
  'channelId': channel_id,
  'part': 'snippet,contentDetails',
  'key': api_key
}, function(data) {
  $.each(data.items, function(i, item) {
    videosArray.push(item);
  });

Now, when I do a console.log(videosArray) I get an object [] and inside it I have the data in ket:value pairs but when I try to read it with another $.each() loop no luck. For example:

0: { 
  kind: "youtube#playlistItem", 
  etag: ""xxsdasdasd"", 
  id: "asdasdad",  
  snippet: {...}, 
  contentDetails: {...}
}

I used dummy data in this example of returned info. Any help is appreciated, thanks !

Here is a full response from console.log(videosArray):

[]
0:{kind: "youtube#playlistItem", etag: ""m2yskBQFythfE4irbTIeOgYYfBU/3QUNPI_1luYHJPo518qq3Jud20E"", id: "UExFbW9VZld4dnFzXzNUbmptdi1GVk1OcHJ1dzZ0M3NQUC41NkI0NEY2RDEwNTU3Q0M2", snippet: {…}, contentDetails: {…}}
1:contentDetails:{videoId: "h9TAxR5wHwc", videoPublishedAt: "2009-08-24T19:02:49.000Z"}etag:""m2yskBQFythfE4irbTIeOgYYfBU/KSpBjTZ-G1a9DM0Pa1kR0rI1RYY""id:"UExFbW9VZld4dnFzLWNvQjJPY0dvdE1fV01rWERiTTN0WC4yODlGNEE0NkRGMEEzMEQy"kind:"youtube#playlistItem"snippet:{publishedAt: "2016-09-01T07:48:18.000Z", channelId: "UCBufHAyKSaGBAIqfjURXCXw", title: ""Yagudky". DakhaBrakha", description: ""Yagudky". DakhaBrakha band (Kyiv, Ukraine)↵http://www.dakhabrakha.com.ua/", thumbnails: {…}, …}
__proto__:Object
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
bookw0rm
  • 27
  • 10
  • You are making the most popular beginner mistake when it comes to working with asynchronous code. All work that you want to do after an asynchronous operation finishes needs to happen *in the callback* for that operation. – Tomalak Aug 14 '17 at 15:52
  • @Tomalak the problem is that I have 5 playlists in 1 channel, and if I iterate the items in the callback I get duplicate of videos, that's why I'm trying to push them outside of the callback. any working examples are appreciated, thanks in advance for the advice. – bookw0rm Aug 14 '17 at 16:05
  • What has "in the callback" with "outside the callback" to do with duplicates? Do you send multiple GET requests or just one? If you send multiple requests and want to wait for all of them, you will need to use `$.when()`. There are many, many examples of how to do that here on SO, take a look around. – Tomalak Aug 14 '17 at 18:27

0 Answers0