此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 –