【问题标题】:How to sort json returned from an API?如何对从 API 返回的 json 进行排序?
【发布时间】: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


【解决方案1】:

这是一个示例,展示了获取艺术家的专辑列表,然后获取每张专辑的流行度值,最后对结果数组进行排序,因此最受欢迎的专辑是数组中的第一个。

  $(document).ready(function () {
        var albums = [], results = [];

        // We start with calling the artist's api
        $.ajax({
            url: "https://api.spotify.com/v1/artists/6vWDO969PvNqNYHIOW5v0m/albums?album_type=album",
            dataType: 'json',
            success: function (data) {

                // Extract the album name and href for the api call
                albums = data.items.map(function (album) {
                    return {
                        name: album.name,
                        href: album.href
                    };
                });

                // Create an array of deferred calls
                var deferreds = albums.map(function (album) {
                    var ajax = $.ajax({
                        url: album.href,
                        dataType: 'json',
                        success: function (data) {
                            // We only care about popularity and name
                            results.push({
                                popularity: data.popularity,
                                name: data.name
                            });
                        }
                    });

                    return ajax;
                });

                // Wait for the album calls to finish
                $.when.apply($, deferreds).then(function() {

                    // Sort on popularity. 
                    results.sort(function (a, b) {
                        if (a.popularity < b.popularity)
                            return 1;
                        else if (a.popularity > b.popularity)
                            return -1;
                        else
                            return 0;
                    });

                    // Results now contains a list of all albums, sorted on popularity
                    alert(results.length);
                });
            }
        });
    });

【讨论】:

  • 我会在标题中补充说,这是一个专门的 jQuery 示例,而不是通用 JS 示例,也不是您可以直接使用的东西...一个 Node.js 应用程序...至少不是原样。
猜你喜欢
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2013-07-08
相关资源
最近更新 更多