【发布时间】:2014-11-18 06:12:18
【问题描述】:
我需要一些关于 Javascript 的帮助。我有一些从 youtube API 收到的数据。数据是从以下 URL 检索的(我只显示了 2 个,但我也从多个其他渠道获得)
这些 json 文件中的每个项目都有“publishedAt”值。现在我想合并两个 JSON 文件中的数据并根据“publishedAt”键对列表进行排序,即首先显示最新上传的视频。
这是我目前拥有的完美适用于一个文件的内容(我没有做任何魔术,URL 本身会根据日期对项目进行排序)
$.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);
};
});
我该如何完成这项工作?
已编辑(我的想法):
我能想到的是使用嵌套对象。我可以创建两个看起来像这样的新对象:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{JSON文件中显示的整个项目}}, {'publishedAt':xxxxxxxx, 'wholeItem':{JSON文件中显示的整个项目2文件}}等}
这里的 parent_object 是 {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
也许我应该首先根据它们的 'publishedAt' 值对 parent_objects 进行排序,然后才能完成这项工作???? PS: parent_object 中的 'publishedAt' 与 'wholeItem' 值中的 'publishedAt' 相同。
解决方案:
我使用了罗斯的逻辑,它奏效了。我对 .getJson 有疑问,因为它不会更新全局变量 Wholearray。所以我使用了 .ajax 并且它起作用了。这是我的工作代码:
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);
}
}
});
}
【问题讨论】:
标签: javascript json youtube