此javascript代码调用spotify api,并返回包含给定艺术家所有专辑的表格。该表中的第5列由一个名为popularity
的值组成。我需要按第五列对表格进行排序,并根据popularity
值打印出前5行(专辑)。如何对从API返回的json进行排序?
$(document).ready(function() {
$("#searchbutton").click(function() {
search();
});
function search() {
var query1 = document.getElementById('querybox').value;
$.get("https://api.spotify.com/v1/search?q=" + query1 + "&type=artist", function (data) {
//alert(data.artists.items[0].id);
getSeveralAlbums(data.artists.items[0].id);
});
}
function getSeveralAlbums(artistid) {
//alert(artistid);
$.getJSON("https://api.spotify.com/v1/artists/" + artistid + "/albums?album_type=album",
function (json) {
//bob = json;
//console.log(json);
for (var i = 0; i < json.items.length; i++) {
getAlbumInfo(json.items[i].href);
//console.log(json.items[i].href);
}
});
}
function getAlbumInfo(albumhref) {
//alert("a");
//console.log("a");
$(document).ready(function() {
$.getJSON(albumhref,
function (json) {
var tr;
// i<json.length
// Sort the array first by popularity. And then create a for loop and print the first five.
tr = $('<tr/>');
tr.append("<td>" + json.name + "</td>"); // Album Name
tr.append("<td>" + json.artists[0].name + "</td>"); // Artist Name
tr.append("<td>" + json.release_date + "</td>"); // Release Date
tr.append("<td>" + json.tracks.total + "</td>"); // Number of Tracks
tr.append("<td>" + json.popularity + "</td>"); // Popularity
$('table').append(tr);
//alert("table compiled");
//alert("Table done");
});
});
}
});
所以我的问题是。获得前5张专辑最有效的方法是什么?我已经有了这些数据,我只需要提供这些数据的一个具体部分。注意:具有所有艺术家专辑列表的API网址不包含所需的popularity
数据。
尝试1: 我试图创建一个二维数组并存储albumhref(api链接返回包含流行度的单个相册数据的json)以及数组单行中每个相册的相应流行度。然后根据受欢迎程度对数组进行排序,然后对albumhref进行理想排序。然后用一个for循环运行一个GET api调用,该循环将获得数组中排序的前五个专辑的专辑数据。这没有奏效。
Arrays returning undefined for API calls (spotify app)
样品API链接到碧昂丝的专辑之一:
https://api.spotify.com/v1/albums/2UJwKSBUz6rtW4QLK74kQu
API链接到所有碧昂丝的专辑列表:
https://api.spotify.com/v1/artists/6vWDO969PvNqNYHIOW5v0m/albums?album_type=album
难道你不能使用'https://api.spotify.com/v1/artists/ {id}/top-tracks'吗? – RRK
理想情况下,您可以使用API来为您排序。如果这不是选项,您可以在客户端对数组进行排序,但取决于数组的大小,这可能会很慢。 – MartijnK
看看这篇文章http://stackoverflow.com/questions/8837454/sort-array-of-objects-by-single-key-with-date-value –