0

I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)

https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A

https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw

Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.

Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)

$.getJSON(sourceUrl, function (data) {
        //console.log(data);
        //var you_data = JSON.stringify(data);
        var videosCount = data.items.length;
        console.log("The number of videos is: " + videosCount);
        for ( i = 0 ;  i < videosCount; i++) {
            var title = data.items[i].snippet.title;
            var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
            $("#reply").append("<a href=\"" + url + "\"> " + title + "</a><br><br><br>");
            //console.log(title);
            //console.log(url);
        };
});

How do I get this done?

EDITED (my thoughts):

Something that I can think of is using nested objects. I can create a new object that two looks something like:

grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}

here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}

Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.

Solution:

I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:

function getAjaxData(sourceUrl) {
$.ajax({
     async:false,
     url:sourceUrl,
     success: function(data) {
         var videosCount = data.items.length;
          for ( var i = 0 ;  i < videosCount; i++) {
              var tempobject = {};
              tempobject.published = data.items[i].snippet.publishedAt;
              tempobject.wholeItem = data.items[i];
              wholearray.push(tempobject);
          }
      }
     });
 }
gixxer
  • 814
  • 1
  • 10
  • 25

1 Answers1

0

One solution is to create a new array of object literals, then sort the array based on the key:

var array = [];
$.getJSON(url, function(data){
   for (var i=0; i<data.length; i++){
      var object = {}
      object.published = data.items[i].snippet.publishedAt
      object.wholeItem = data.items[i]
      array.push(object);
    }
 })
$.getJSON(otherUrl, function(data){
   for (var i=0; i<data.length; i++){
      var object = {}
      object.published = data.items[i].snippet.publishedAt
      object.wholeItem = data.items[i]
      array.push(object);
    }
 })

Have a listener that waits for both AJAX calls to finish, then you can sort:

array.sort(function(a,b) { return a.published - b.published; });

This question gives more info on sorting

This may not be the most efficient way, but it's the first that comes to mind and will work swell!

Community
  • 1
  • 1
RossHochwert
  • 160
  • 10
  • I had a similar idea but I used your code. However I am stuck at a point where the "array" is not being updated. I declared "array" as a global variable, and when I try to update that variable from inside ".getJSON" function, it doesn't work. Updating it from any other function works except this .getJSON. The same issue exists for any other global variable. I couldn't paste my code in this comment, will paste in the next comment. – gixxer Nov 18 '14 at 08:08
  • `var wholearray = []; << global variable function getYouTubeUrls(sourceUrl) { $.getJSON(sourceUrl, function (data) { var videosCount = data.items.length; for ( var i = 0 ; i < videosCount; i++) { var tempobject = {} tempobject.published = data.items[i].snippet.publishedAt; tempobject.wholeItem = data.items[i]; wholearray.push(tempobject); console.log(wholearray); }; });` – gixxer Nov 18 '14 at 08:14
  • Can you post a JSFiddle? Also your key doesn't seem to work anymore with the API which could be causing issues. – RossHochwert Nov 18 '14 at 17:53