【发布时间】:2016-03-02 07:35:58
【问题描述】:
这段 javascript 代码调用了 spotify api,它返回了一个包含给定艺术家的所有专辑的表格。该表中的第 5 列包含一个名为 popularity 的值。我需要按第五列对表格进行排序,并根据popularity 值打印出前 5 行(专辑)。
$(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 url 不包含必需的 popularity 数据。
尝试 1: 我尝试创建一个二维数组并存储albumhref(api链接以返回json,其中包含单个专辑的数据,其中包括流行度),以及数组的单行中每个专辑的相应流行度。然后根据流行度对数组进行排序,理想情况下也对专辑引用进行排序。然后使用 for 循环运行 GET api 调用,该循环将从将要排序的数组中获取前五个专辑的专辑数据。这不起作用。
Arrays returning undefined for API calls (spotify app)
Beyonce 专辑之一的示例 API 网址:
https://api.spotify.com/v1/albums/2UJwKSBUz6rtW4QLK74kQu
列出所有 Beyonce 专辑的 API url:
https://api.spotify.com/v1/artists/6vWDO969PvNqNYHIOW5v0m/albums?album_type=album
【问题讨论】:
-
你不能用
https://api.spotify.com/v1/artists/{id}/top-tracks吗? -
理想情况下,您可以获得 API 来为您进行排序。如果这不是选项,您可以在客户端对数组进行排序,但根据数组的大小,这可能会很慢。
-
@RejithRKrishnan 我曾想过使用该端点,但问题是热门曲目并不总是在热门专辑中。而且一张专辑可能有多个艺术家的热门曲目,因此表格会有行的副本。
标签: javascript json api spotify