简体   繁体   中英

How to sort json returned from an API?

This javascript code makes a call to the spotify api and it returns a table with all the albums of a given artist. The 5th column in that table consists of a value called popularity . I need to sort the table by fifth column and print out the top 5 rows(albums) based on popularity values.

$(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");
            });
        });
    }
});

So my questions is. What is the most efficient way to get the top 5 albums? I already have the data, I just need to present a specific subsection of that data. Note: The API url with a list of all the artists albums does not contain the popularity data which is required.

Attempt 1: I tried to create a 2D array and store the albumhref(api link to return json with a single album's data which includes popularity), and corresponding popularity for each album in a single row of the array. Then sort the array based on popularity which would ideally sort the albumhref's also. Then run a GET api call with a for loop which would get the album data for the first five albums from the array which would be sorted. This didn't work.

Arrays returning undefined for API calls (spotify app)


Sample API url to one of Beyonce's albums:

https://api.spotify.com/v1/albums/2UJwKSBUz6rtW4QLK74kQu

API url to list of all Beyonce's albums:

https://api.spotify.com/v1/artists/6vWDO969PvNqNYHIOW5v0m/albums?album_type=album

Here's a example to show getting the artist's album list and then each album for it's popularity value, and finally sort the resulting array, so the most popular album is the first in the array.

  $(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);
                });
            }
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM